【问题标题】:How to Instantiate @configuration bean based on property value from properties file如何根据属性文件中的属性值实例化 @configuration bean
【发布时间】:2018-01-16 12:32:45
【问题描述】:

我有两个用@Configuration 注释的类/bean,我必须实例化 基于属性文件中的值。

RemoteServer1.java

@Configuration
public class RemoteServer1 {
    //some authentication logic goes here
}

RemoteServer2.java

@Configuration
public class RemoteServer2 {
    //some authentication logic goes here
}

application.properties

remote.server.location=RemoteServer1

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

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    我建议您查看 Spring Boot 中的 @Contidional... 注释,以有条件地激活 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)
    

    第二,

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

    查找属性name,匹配havingValue,如果缺少该属性,则不会评估为true

    【讨论】:

      【解决方案2】:

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

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

      它将拉取值并将其自动配置到字符串

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        • 2023-03-08
        • 1970-01-01
        • 2022-01-14
        • 2013-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多