【问题标题】:env.getProperty not working Spring PropertyPlaceholderConfigurerenv.getProperty 不工作 Spring PropertyPlaceholderConfigurer
【发布时间】:2014-07-16 17:58:59
【问题描述】:

我正在使用 spring 加载属性文件

  <bean id="appProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="locations" value="classpath:/sample.properties" />
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

当我使用

获取属性值时

@Value("${testkey}") 工作正常。

但是当我尝试使用 env 时

@Resource
 private Environment environment;

environment.getProperty("testkey") // returning null

【问题讨论】:

    标签: java spring spring-4


    【解决方案1】:

    PropertyPlaceholderConfigurer 不会将其locations 中的属性添加到Environment。使用 Java 配置,您可以使用 @PropertySource 来执行此操作。

    【讨论】:

    • 春天 4 有没有办法通过 xml 做?
    • @invariant 我不知道通过声明一个 bean 来做到这一点的干净方法。您可以创建自己的 ApplicationContextAware bean 来添加它们。
    【解决方案2】:

    如果有人想在不使用@PropertySource 的情况下实现这一目标

    使用 ApplicationContextInitializer 接口及其配套的 contextInitializerClasses servlet 上下文参数。

    在 web.xml 中添加这个

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

    并定义你的初始化器

    public class MyInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
        public void initialize(ConfigurableWebApplicationContext ctx) {
            PropertySource ps = new ResourcePropertySource(new ClassPathResource("sample.properties")); // handle exception
            ctx.getEnvironment().getPropertySources().addFirst(ps);
        }
    }
    

    参考:Spring 3.1 M1: Unified Property Management

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2013-02-21
      • 2011-11-24
      • 2011-06-28
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多