springboot可以使用ConfigurationProperties将配置映射为对象,假设有一个服务器列表的配置,服务器拥有ip,端口,名字三个属性,配置文件如下:
servers.ips[0]=127.0.0.1 servers.ports[0]=9090 servers.names[0]=Server1 servers.ips[1]=127.0.0.2 servers.ports[1]=9092 servers.names[1]=Server2
可以创建映射对象并添加@ConfigurationProperties注解与配置文件相关联
@ConfigurationProperties("servers") public class Servers { private List<String> ips; private List<Integer> ports; private List<String> names; public void setIps(List<String> ips) { if (null != this.ips) { return; } this.ips = ips; } public void setPorts(List<Integer> ports) { if (null != this.ports) { return; } this.ports = ports; } public void setNames(List<String> names) { if (null != this.names) { return; } this.names = names; } public String getIp(int index) { return ips.get(index); } public Integer getPort(int index) { return ports.get(index); } public String getName(int index) { return names.get(index); } public int count() { return ips.size(); } }
在数据不为空时,不允许set数据,并且不提供getter方法以防止对数据进行修改
为了使配置映射可以被扫描到,需要在@Configuration所注解的类中,添加@EnableConfigurationProperties(Servers.class),可以直接使用@Autowired引用配置类
代码示例如下:
@RestController @EnableAutoConfiguration @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(Servers.class) public class HelloWorld { @Autowired private Servers servers; @RequestMapping("/") String listServers() { int count = servers.count(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < count; i++) { sb .append(servers.getIp(i)) .append(" ~ ") .append(servers.getPort(i)) .append(" ~ ") .append(servers.getName(i)) .append("<br/>"); } return sb.toString(); } public static void main(String[] args) { SpringApplication app = new SpringApplication(HelloWorld.class); app.run(args); } }
访问http://localhost:8080/可以看到所有的服务器数据:
127.0.0.1 ~ 9090 ~ Server1 127.0.0.2 ~ 9092 ~ Server2