Spring 3.1 环境不适用于用户属性文件

2022-09-02 21:46:56

我正在这样做..

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();

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

@Autowired
private Environment env
.....
env.getProperty("my.property")

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

@Value("${my.property}")
private String myProperty;

我甚至尝试像这样再添加几行,但没有用。

ConfigurableEnvironment env = new StandardEnvironment();
propertyHolder.setEnvironment(env);

有谁知道为什么我的属性没有加载到环境中?谢谢。


答案 1

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

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

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

我相信你可以以编程方式做同样的事情,即你可以在刷新上下文之前获得容器的可配置环境,修改它的可变属性源(你需要首先通过)来获取属性,但这不太可能是你想做的 - 如果你已经有一个带注释的类,用它来装饰它要简单得多。AbstractApplicationContextenvironmentcontext.getEnvironment()getPropertySources().addFirst(new ResourcePropertySource(new ClassPathResource( "SpringConfig.properties")));@Configuration@PropertySource("classpath:SpringConfig.properties")

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

有关自定义属性源实现的示例,请参见 http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/


答案 2

本地属性添加到 PropertySourcesPlaceholderConfigurer(使用 or )不会使它们在 .setProperties()setLocation()Environment

实际上,它以相反的方式工作 - 充当属性的主要来源(请参阅可配置环境),并且可以从可用的使用语法中生成属性。EnvironmentPropertySourcesPlaceholderConfigurerEnvironment${...}


推荐