由于这里我想通过java连接linux,connection连接需要host、port、username、password及其他路径等等。不想每次修改的时候都去改源文件,所以想写在application.yml配置文件中,然后读取。
首先需要在pom.xml中增加以下依赖,支持 @ConfigurationProperties 注解
<!-- 支持 @ConfigurationProperties 注解 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
然后再application.yml配置文件中增加我需要的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:WorkSpaceeast-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) 服务器连接成功. ch.ethz.ssh2.Connection@38ee7a9d 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'