如何根据属性文件中的属性值实例化@configuration bean

问题描述:

我有两个使用@configuration注解的类/ bean,我必须根据属性文件中的值实例化 。如何根据属性文件中的属性值实例化@configuration bean

RemoteServer1.java

@Configuration
公共类RemoteServer1 {
//一些验证逻辑放在这里
}



RemoteServer2.java

@配置
公共类RemoteServer2 {
//一些验证逻辑放在这里
}


application.properties
remote.server.location = RemoteServer1

现在我想要实例化与属性文件中的值匹配的@Configuration类/ bean。

我建议你看看在春天开机@Contidional...注释有条件地激活豆类,配置等

http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html

应该工作看属性和配置。对于第一构造,

@ConditionalOnProperty(name="remote.server.location", havingValue="RemoteServer1", matchIfMissing=false)

其次,

@ConditionalOnProperty(name="remote.server.location", havingValue="RemoteServer2", matchIfMissing=false)

看起来的财产name,在havingValue匹配,如果缺少该属性将不计算为true

+0

它的工作非常感谢@Darren福赛斯 – laxmi

如果要对属性文件进行引用,请使用“$ {}”语法。例如,

@Value("${some.prop}") 
private String remoteServer 

这将拉动值,并将其自动配置到字符串