由于这里我想通过 java 连接 Linux,connection 连接需要 host,port,username,password 及其他路径等等. 不想每次修改的时候都去改源文件, 所以想写在 application.YAML 配置文件中, 然后读取.
首先需要在 pom.xml 中增加以下依赖, 支持 @ConfigurationProperties 注解
- <!-- 支持 @ConfigurationProperties 注解 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-configuration-processor</artifactId>
- <optional>true</optional>
- </dependency>
然后再 application.YAML 配置文件中增加我需要的 SSH 常量.
- SSH:
- host: 192.168.8.100
- port: 22
- username: root
- password: password
创建一个 bean 接收常量, 需要 @ConfigurationProperties 注解
@Data 为 lombok 注解省略 setter 和 getter
@Component 注册为 bean
@ConfigurationProperties 读取配置文件
- package com.easyci.ci.entity;
- import lombok.Data;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.stereotype.Component;
- @Data
- @Component
- @ConfigurationProperties("ssh") // 接收配置文件中 "ssh" 下的属性值
- public class SshProperties {
- private String host;
- private Integer port;
- private String username;
- private String password;
- }
测试:
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class CiApplicationTests {
- @Autowired
- private SshProperties sshProperties;
- @Test
- public void contextLoads() {
- Connection con = ConnectUtil.getConnect(sshProperties.getHost(),sshProperties.getUsername(),sshProperties.getPassword(),sshProperties.getPort());
- System.out.println(con);
- }
- }
结果:
- . ____ _ __ _ _
- /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ ( ( )\___ |'_ | '_| |'_ \/ _` | \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) )
- ' |____| .__|_| |_|_| |_\__, | // //
- =========|_|==============|___/=/_/_/_/
- :: Spring Boot :: (v2.1.8.RELEASE)
- 2019-09-26 09:58:12.540 INFO 7420 --- [ main] com.easyci.ci.CiApplicationTests : Starting CiApplicationTests on DESKTOP-ANG78AB with PID 7420 (started by jxd in D:\WorkSpace\east-ci)
- 2019-09-26 09:58:12.540 INFO 7420 --- [ main] com.easyci.ci.CiApplicationTests : No active profile set, falling back to default profiles: default
- 2019-09-26 09:58:13.448 INFO 7420 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
- 2019-09-26 09:58:13.660 INFO 7420 --- [ main] com.easyci.ci.CiApplicationTests : Started CiApplicationTests in 1.345 seconds (JVM running for 2.042)
服务器连接成功.
- [email protected]
- 2019-09-26 09:58:14.218 INFO 7420 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
- Disconnected from the target VM, address: '127.0.0.1:54934', transport: 'socket'
来源: http://www.bubuko.com/infodetail-3213501.html