gpt4 book ai didi

java - 从 spring 上下文实例化自定义 PropertySourcesPlaceholderConfigurer

转载 作者:行者123 更新时间:2023-11-29 05:30:23 26 4
gpt4 key购买 nike

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

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

似乎是spring应该提供的基本东西,但是从昨天开始我找不到办法去做。使用命名空间将使我能够加载多个属性文件,但我还需要定义 PropertySourcesPlaceholderConfigurer 的 ID(其他项目引用它),而且我还想使用我的自定义实现。这就是我显式定义 bean 而不使用命名空间的原因。

最直观的方法是像这样将 PropertySources 列表注入(inject) 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 接口(interface)有一个也是唯一的实现者,它是 MutablePropertySources,它确实存储了 PropertySource 对象的列表,但没有构造函数或 setter,我可以通过它注入(inject)这个列表。它只有 add*(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 上下文实例化自定义 PropertySourcesPlaceholderConfigurer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21306341/

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