Java 从spring上下文实例化自定义属性资源占位符配置器

Java 从spring上下文实例化自定义属性资源占位符配置器,java,spring,Java,Spring,我想在spring上下文xml中定义一个自定义PropertySourcesPlaceholderConfigurer。我想在那里使用多个PropertySource,这样我就可以从多个属性文件加载部分配置,并通过自定义PropertySource实现动态提供其他部分。这样做的好处是,只需修改XMLSpring配置,就可以轻松地调整加载这些属性源的顺序 在这里我遇到了一个问题:如何定义任意的PropertySources列表并将其注入PropertySourcesPlaceholderConfi

我想在spring上下文xml中定义一个自定义PropertySourcesPlaceholderConfigurer。我想在那里使用多个PropertySource,这样我就可以从多个属性文件加载部分配置,并通过自定义PropertySource实现动态提供其他部分。这样做的好处是,只需修改XMLSpring配置,就可以轻松地调整加载这些属性源的顺序

在这里我遇到了一个问题:如何定义任意的PropertySources列表并将其注入PropertySourcesPlaceholderConfigurer,以便它使用我定义的源

这似乎是spring应该提供的基本功能,但从昨天开始,我就找不到一个方法来实现它。使用名称空间将使我能够加载多个属性文件,但我还需要定义PropertySourcesPlaceholderConfigurer的id(正如其他项目所引用的),并且我还希望使用自定义实现。这就是我显式定义bean而不使用名称空间的原因

最直观的方法是将PropertySources列表注入PropertySourcesPlaceholder配置器,如下所示:

<bean id="applicationPropertyPlaceholderConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="ignoreResourceNotFound" value="true" />     
    <property name="order" value="0"/>
    <property name="propertySources">
        <list>
             <!-- my PropertySource objects -->
        </list>
    </property> 
</bean>

但不幸的是,propertySources属于propertySources类型,不接受列表。PropertySources接口有一个也是唯一一个实现器,它是可变PropertySources,它确实存储PropertySources对象的列表,但没有构造函数或setter,我可以通过它们注入这个列表。它只有add*(PropertySource)方法

我现在看到的唯一解决方法是实现我自己的PropertySources类,扩展MutablePropertySources,它将在创建时接受PropertySource对象列表,并通过使用add*(PropertySource)方法手动添加它。但是为什么需要这么多的变通方法来提供一些我认为应该是引入PropertySources的主要原因(从spring配置级别可以管理灵活的配置)


请澄清我错在哪里:)

我使用java配置,不知道在spring版本之间是否有任何字段更改,但它可能会帮助您:

 public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
        properties.setLocations(new ClassPathResource[]{
                new ClassPathResource("config/file1.properties"),
                new ClassPathResource("config/file2.properties")
        });
        properties.setLocalOverride(true);
        properties.setBeanName("beanName");
        properties.setIgnoreResourceNotFound(true);
        return properties;
    }
而不是

<property name="propertySources">
        <list>
             <!-- my PropertySource objects -->
        </list>
</property> 

使用类似于:

    <property name="locations">
        <list>
            <value>/WEB-INF/my.properties</value>
            <value>classpath:my.properties</value>
        </list>
    </property>

/WEB-INF/my.properties
类路径:my.properties

我真正需要的不是来自多个不同位置的属性资源,而不仅仅是来自属性文件,位置仅用于类路径资源。。我认为这是在Spring3.1中引入PropertySourcesPlaceholderConfigurer之前已经存在的。。我现在想以某种巧妙的方式利用这个新类。它接受org.springframework.core.io.Resource的实现,因此ClassPathResource不是唯一的选项:)在这种情况下,您到底想设置什么作为属性?我想设置PropertySource的自定义实现(我自己实现PropertySource的类)它将在运行时内部调用另一个服务来获取属性。