1

我目前正在使用PropertyPlaceholderConfigurer将属性加载到我的 spring 上下文中,但是我想要一个自定义层次结构/覆盖我在 Java 类中处理的属性文件。我可以让我的类(它本身是上下文中的一个 bean)将属性注入到上下文中吗?

例如

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:/config/conf.properties" />
</bean>

<bean id="config" class="com.main.Config" />

我的 Config 类有一个Properties getProperties() 方法——我能以某种方式将它连接到 spring 中吗?显然,在创建或初始化配置 bean 之前不会加载属性。

谢谢!

更新:正如答案所建议的,我将我的配置更改为Config extends PropertySource<Properties>并且必须编写一个小包装器,MutablePropertySources它需要一个PropertySource,然后我的 xml 看起来像这样:

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="propertySources">
        <bean class="com.main.ConfigMutablePropertySources">
             <constructor-arg name="propertySource" ref="config" />
        </bean>
    </property>
</bean>

在哪里:

public class ConfigMutablePropertySources extends MutablePropertySources {
    public ConfigMutablePropertySources(PropertySource<?> propertySource) {
        super(new MutablePropertySources());
        addLast(propertySource);
    }
}
4

1 回答 1

0

查看可用的方法(来自JavaDoc forPropertyPlaceholderConfigurer)向我表明没有简单的方法来做这样的事情。

顶部的一般性评论表明,从 Spring 3.1 开始,应该更喜欢使用它PropertySourcesPlaceholderConfigurer。使用此解决方案,您似乎可以PropertySource通过setPropertySources(...)方法注册自己的对象集。当然,您的Config类必须适合PropertySource.

值得注意的是,使用上述setPropertySources(...)方法不会假设您的属性源没有其他任何内容,因此不会添加默认属性源(环境和本地属性)。

于 2013-06-10T17:27:50.350 回答