gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:52:49 25 4
gpt4 key购买 nike

我正在这样做..

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

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

最佳答案

PropertySourcesPlaceholderConfigurer 直接读取属性文件(就像在 Spring 3.0 中由 PropertyPlaceholderConfigurer 所做的那样),它只是一个后处理器,不会改变在 Spring 上下文中使用属性的方式 - 在这种情况下,属性只能用作 bean 定义占位符.

使用 Environment 的是 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/

关于java - Spring 3.1 环境不适用于用户属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14169834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com