在没有PropertyPlaceholderConfigurer的情况下获取Spring属性@Value

时间:2016-09-21 11:15:00

标签: spring spring-boot

我无法使用@Value注释获取spring application.properties中定义的属性。不知怎的,我知道我们必须在rootConfig中注册propertysourcesplaceholderconfigurer bean,这个注册方法是 static

 @Bean 
 public static PropertyPlaceholderConfigurer properties() {

     PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
     ClassPathResource[] resources = new ClassPathResource[ ] {
         new ClassPathResource("db.properties")
     };
     ppc.setLocations( resources );
     ppc.setIgnoreUnresolvablePlaceholders( true );
     ppc.setSearchSystemEnvironment(true);
     return ppc;
}

此处的问题是来自 cmis application.properties ,并且仅在创建applicationContext时初始化资源加载器。完成applicationContext后,在rootConfig中,通过Environment.getProperty(XXX),可以获取属性值。

还有其他方法吗?

修改

我想知道即使我可以使用@conditionOnProperty访问该属性而不使用PropertyPlaceholderConfigurer。有没有类似的方法?

1 个答案:

答案 0 :(得分:0)

<强> application.propertes

application.angular.rooturl = http://localhost:8080/test

我使用@value

的Java类
@Configuration
@PropertySource(value="classpath:application.properties")
public class ApplicationPropertyConfig {

    public static String ROOTURL;

    @Value("${application.angular.rooturl}")
    public void setANGULAR_ROOTURL(String aNGULAR_ROOTURL) {
        ANGULAR_ROOTURL = aNGULAR_ROOTURL;
    }
}

然后我可以使用ApplicationPropertyConfig.ROOTURL

获取此值
相关问题