我试图弄清楚如何将属性文件的值添加到我的Spring Environment属性中。

Spring 3.1之前的实现方式如下:

  <context:property-placeholder location="classpath:my.properties" />

  <bean id="myBean" class="com.whatever.MyBean">
    <property name="someValue" value="${myProps.value}" />
    <!-- etc -->
  </bean>


我也可以这样做:

public class MyBean {

   @Value(value = "#{myProps.value}")
   private String someValue;

}


现在,从表面上看,我可以从Environment类中提取属性,这比在XML或bean本身中使用笨拙的#{myProps.value}语法似乎是一种获取属性的更简洁的方法。

我在XML中尝试了此操作:

<bean
    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location">
        <value>classpath:my.properties</value>
    </property>
</bean>


但是属性未添加到环境中。

我知道可以使用PropertySource属性,但是我没有使用注释进行配置。

那么,如何设置bean / xml,以便在环境中可以使用props中设置的变量?此外,如何将那些值注入到我的bean中,而不必明确地说“ environmentInstance.getProperty(“ myProps.value”)?

最佳答案

对于Web应用程序

如果要在处理XML bean定义之前先填充Environment,则应实现ApplicationContextInitializer(),如the Spring Source blog中所述

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.bank.MyInitializer</param-value>
</context-param>


这是博客中示例的略微修改版本

public class MyInitializer implements
        ApplicationContextInitializer<ConfigurableWebApplicationContext> {
    public void initialize(ConfigurableWebApplicationContext ctx) {
        ResourcePropertySource ps;
        try {
            ps = new ResourcePropertySource(new ClassPathResource(
                    "my.properties"));
        } catch (IOException e) {
            throw new AssertionError("Resources for my.properties not found.");
        }
        ctx.getEnvironment().getPropertySources().addFirst(ps);
    }
  }


对于独立应用

基本上是一样的,您可以直接修改AbstractApplicationContext的环境

   ResourcePropertySource ps;
   try {
        ps = new ResourcePropertySource(new ClassPathResource(
                        "my.properties"));
   }catch (IOException e) {
                throw new AssertionError("Resources for my.properties not found.");
   }
   //assuming that ctx is an AbstractApplicationContext
   ctx.getEnvironment().getPropertySources().addFirst(ps);


附言该答案的早期版本显示了尝试从Bean修改环境的尝试,但这似乎是在SO上展开的反模式,因为可以肯定的是,甚至在XmlBeanDefinitionReader开始处理XML之前,您都希望填充环境属性源列表。使占位符在<import/>语句中起作用。

07-28 02:33
查看更多