Spring 3.1 Environment不适用于用户属性文件

end*_*ess 17 java spring

我这样做..

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
xmlReader
        .loadBeanDefinitions(new ClassPathResource("SpringConfig.xml"));
PropertySourcesPlaceholderConfigurer propertyHolder = new PropertySourcesPlaceholderConfigurer();
propertyHolder.setLocation(new ClassPathResource(
        "SpringConfig.properties"));
context.addBeanFactoryPostProcessor(propertyHolder);

    ......

context.refresh();
Run Code Online (Sandbox Code Playgroud)

现在在我的@Configuration文件中,如果我这样做,我的SpringConfig.properties中存在的属性就不会被拾取...

@Autowired
private Environment env
.....
env.getProperty("my.property")
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用,我会获得该属性

@Value("${my.property}")
private String myProperty;
Run Code Online (Sandbox Code Playgroud)

我甚至尝试添加这样的更多行,但没有用.

ConfigurableEnvironment env = new StandardEnvironment();
propertyHolder.setEnvironment(env);
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么我的属性没有加载到Environment中?谢谢.

Bor*_*hov 15

PropertySourcesPlaceholderConfigurer直接读取属性文件(因为它是由PropertyPlaceholderConfigurer在Spring 3.0中完成的),它只是一个后处理器,它不会改变Spring上下文中使用属性的方式 - 在这种情况下,属性仅可用作bean定义占位符.

它是使用环境的PropertySourcesPlaceholderConfigurer,反之亦然.

属性源框架在应用程序上下文级别上工作,而属性占位符配置器仅提供在bean定义中处理占位符的功能.要使用属性源抽象,您应该使用@PropertySource注释,即用类似的东西装饰您的配置类 @PropertySource("classpath:SpringConfig.properties")

我相信您可以通过编程方式执行相同的操作,即您可以在刷新上下文之前获取容器的ConfigurableEnvironment,修改其MutablePropertySources(您首先需要获取AbstractApplicationContext environment属性context.getEnvironment() )getPropertySources().addFirst(new ResourcePropertySource(new ClassPathResource( "SpringConfig.properties")));但是您不太可能想要做什么 - 如果您已经拥有一个带@Configuration注释的类,装饰它@PropertySource("classpath:SpringConfig.properties")更简单.

至于PropertySourcesPlaceholderConfigurer实例 - 它将从其应用程序上下文中自动获取属性源(因为它实现了EnvironmentAware),因此您只需要注册它的默认实例.

对于自定义属性代码实现的例子中看到http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/

  • 也许您可以尝试使用addLast而不是addFirst或类似的东西 - 以便首先处理系统属性. (2认同)