簡體   English   中英

從spring上下文實例化自定義PropertySourcesPlaceholderConfigurer

[英]Instantiating custom PropertySourcesPlaceholderConfigurer from spring context

我想在spring上下文xml中定義一個自定義的PropertySourcesPlaceholderConfigurer。 我想在那里使用多個PropertySources,這樣我就可以從幾個屬性文件中加載部分配置,並通過我的自定義PropertySource實現動態地提供其他部分。 優點是,只需通過修改xml彈簧配置就可以輕松調整加載這些屬性源的順序。

在這里我遇到了一個問題:如何定義一個任意的PropertySources列表並將其注入PropertySourcesPlaceholderConfigurer,以便它使用我定義的來源?

似乎是一個應該由春天提供的基本事物,但從昨天起我無法找到辦法。 使用命名空間可以讓我加載幾個屬性文件,但我還需要定義PropertySourcesPlaceholderConfigurer的id(正如其他項目引用它),我也想使用我的自定義實現。 這就是我明確定義bean而不使用命名空間的原因。

最直觀的方法是將PropertySources列表注入PropertySourcesPlaceholderConfigurer,如下所示:

<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接口有一個唯一的實現者,它是MutablePropertySources,它確實存儲了PropertySource對象的列表,但沒有構造函數或setter,我可以通過它來注入這個列表。 它只有添加*(PropertySource)方法。

我現在看到的唯一解決方法是實現我自己的PropertySources類,擴展MutablePropertySources,它將在創建時接受PropertySource對象列表,並通過使用add *(PropertySource)方法手動添加它。 但是為什么需要這么多的解決方法來提供我認為應該是引入PropertySources的主要原因(具有靈活的配置可以從spring配置級別進行管理)。

請澄清我弄錯了什么:)

代替

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

我使用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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM