springboot读取自定义配置
application.yml自定义配置
my-app:ip1:#dmz1 ftp服务器ipAddress: 172.12.23.456port: 21username: adminpassword: adminip2:ipAddress: 172.12.23.457port: 21username: adminpassword: admin
方式1,@Value注解
@Component
public class IpConfig {@Value("${my-app.ip1.ipAddress}")public String ipAddress1;@Value("${my-app.ip1.port}")public Integer port1;@Value("${my-app.ip1.username}")public String username1;@Value("${my-app.ip1.password}")public String password1;@Value("${my-app.ip2.ipAddress}")public String ipAddress2;@Value("${my-app.ip2.port}")public Integer port2;@Value("${my-app.ip2.username}")public String username2;@Value("${my-app.ip2.password}")public String password2;
}
测试取值
@Component
public class TaskConfiguration {private final IpConfig ipConfig;@AutowiredTaskConfiguration(IpConfig ipConfig) {this.ipConfig= ipConfig;}@PostConstructpublic void task1() {//172.12.23.456String ipAddress1 = ipConfig.getIpAddress1();}
方式2,@ConfigurationProperties(prefix = “my-app”)注解
@Component
@ConfigurationProperties(prefix = "my-app")
@Data
public class MyApp {private Ip1 ip1;private Ip2 ip2;@Datapublic static class Ip1 {private String ipAddress;private int port;private String username;private String password;}@Datapublic static class Ip2 {private String ipAddress;private int port;private String username;private String password;}
}
测试@ConfigurationProperties注解取值
@Component
public class TaskConfiguration {private final String ipAddress1;private final String ipAddress2;@AutowiredTaskConfiguration(MyApp myApp) {this.ipAddress1 = myApp.getIp1().getIpAddress();this.ipAddress2 = myApp.getIp2().getIpAddress();}@PostConstructpublic void task1() {System.out.println(ipAddress1);System.out.println(ipAddress2);}
}
参考文档
springboot类型安全的绑定(使用@ConfigurationProperties注解一次性拿到application.yml 配置文件中的多个属性值)