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

lax*_*xmi 2 spring spring-boot

我有两个带有注释的类/bean @Configuration,我必须根据属性文件中的值进行实例化。

远程服务器1.java

@Configuration
public class RemoteServer1 {
    //some authentication logic goes here
}
Run Code Online (Sandbox Code Playgroud)

远程服务器2.java

@Configuration
public class RemoteServer2 {
    //some authentication logic goes here
}
Run Code Online (Sandbox Code Playgroud)

应用程序属性

remote.server.location=RemoteServer1
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*the 6

我建议您查看@Contidional...Spring Boot 中的注释,以有条件地激活 Bean、配置等。

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)
Run Code Online (Sandbox Code Playgroud)

第二,

@ConditionalOnProperty(name="remote.server.location", havingValue="RemoteServer2",  matchIfMissing=false)
Run Code Online (Sandbox Code Playgroud)

查找属性name,匹配于havingValuetrue如果属性丢失,则不会评估。