我有一个属性文件,用于定义动态端点(名称,主机和端口)。
所以我创建了一个名为EndPoint
的bean,其名称,主机和端口作为成员变量。
如何使用Spring @Value
和SpEL动态注入服务器的主机和端口?
endpoint.properties
names=server1,server2,server3
endpoint.server1.host=192.168.1.101
endpoint.server1.port=10101
endpoint.server2.host=192.168.1.102
endpoint.server2.port=10102
endpoint.server3.host=192.168.1.103
endpoint.server3.port=10103
EndPoint.java
public class EndPoint {
/** name */
private String name;
// hardcode server1 here
// how to inject server's host dynamically by name?
// @Value("${endpoint.#{this.name}.host}")
@Value("${endpoint.server1.host}")
private String host;
@Value("${endpoint.server1.port}")
private int port;
public EndPoint(String name) {
this.name = name;
}
}
EndPointBeanConfig.java
@Configuration
@PropertySource( //
value = { "classpath:conf/endpoint.properties" }, ignoreResourceNotFound = true//
)
public class EndPointBeanConfig {
@Autowired
private Environment env;
@Bean(name = "endPoints")
public List<EndPoint> endPoints() {
final List<EndPoint> endPoints = new ArrayList<EndPoint>();
final String[] names = env.getProperty("names").split(",");
for (final String name : names) {
final EndPoint endPoint = endPoint(name);
endPoints.add(endPoint);
}
return endPoints;
}
@Bean(name = "endPoint")
@Scope("prototype")
public EndPoint endPoint(String name) {
return new EndPoint(name);
}
}