由于这里我想通过java连接linux,connection连接需要host、port、username、password及其他路径等等。不想每次修改的时候都去改源文件,所以想写在application.yml配置文件中,然后读取。
首先需要在pom.xml中增加以下依赖,支持 @ConfigurationProperties 注解
org.springframework.boot
spring-boot-configuration-processor
true
然后再application.yml配置文件中增加我需要的ssh常量。
ssh:
host: 192.168.8.100
port: 22
username: root
password: password
创建一个bean接收常量,需要 @ConfigurationProperties 注解
@Data为lombok注解省略setter和getter
@Component 注册为bean
@ConfigurationProperties 读取配置文件
packagecom.easyci.ci.entity;importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties("ssh") //接收配置文件中“ssh”下的属性值public classSshProperties {privateString host;privateInteger port;privateString username;privateString password;
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTestpublic classCiApplicationTests {
@AutowiredprivateSshProperties sshProperties;
@Testpublic voidcontextLoads() {
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)
服务器连接成功.
ch.ethz.ssh2.Connection@38ee7a9d2019-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'