java - 使用 Spring 覆盖外部属性文件中的属性(如果存在)

标签 java spring properties

我的 Spring 配置文件之一中定义了以下属性文件:

<context:property-placeholder location="classpath:project.properties"/> 

现在我想覆盖一些不在类路径中的外部属性文件中的一些属性。

假设我的项目部署在某个地方,我需要进行一些动态配置更改。我不想更新容器(tomcat 或任何东西)中的项目代码库。

1.) 所以我需要一种方法,用我最近在外部属性文件中的更新来更新(覆盖)spring 加载的属性文件的值。

2.) 如果有人也可以分享刷新预加载属性的方法,那就太好了。

最佳答案

So I need a way that updates (overrides) the values of spring's loaded properties file with my recent updates in the external property file.

您可以使用 PropertyPlaceholderConfigurer .

如果要使用context命名空间

<context:property-placeholder location="classpath:yourClasspath.properties,file:/some/resource/path/filePropertiesToOverride.properites"/> 

或者这样

<bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:yourClasspath.properties</value>
            <value>file:/some/resource/path/filePropertiesToOverride.properites</value>
        </list>
    </property>
</bean>

根据 PropertiesLoaderSupport.setLocations(Resource[]) 的 javadoc

... Note: Properties defined in later files will override properties defined earlier files, in case of overlapping keys. Hence, make sure that the most specific files are the last ones in the given list of locations.

.

It would be great if somebody could also share the way to refresh the properties that are preloaded.

目前您正在使用 PropertyPlaceholderConfigurer。由于 PropertyPlaceholderConfigurerBeanFactoryPostProcessor,它会遍历 bean 定义(beans.xml 的对象表示)并替换属性字符串(例如 $ {someProp})。之后,bean 被实例化和初始化。因此无法“重新加载”属性。

如果您想构建一个可以在运行时对属性更改使用react的应用程序,还有更多需要考虑的因素:

  • 如何在运行时触发更改?例如。轮询属性文件以进行更改、JMX、...的计时器?
  • 如何将更新通知依赖于属性的类?例如。监听器实现。
  • 如何同步多个依赖属性的更新?例如。想象一下,如果在没有同步的 Web 应用请求期间更新属性会发生什么。请求的一部分可能使用旧属性,另一部分使用新属性。

至少我会推荐使用 apache commons configuration .但它只是一个解决了几个问题的框架,对于上面的问题,你仍然需要思考解决方案。

关于java - 使用 Spring 覆盖外部属性文件中的属性(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21015278/

相关文章:

c# Image PropertyItems (Metadate) 你怎么知道哪个数字是哪个属性?

spring - 如何在 YML 中表示带有值和子属性的 Spring 属性?

java - 在 for 循环中绘制图像 x 次

java - Hibernate启用自定义修订版实体

java - Spring - 为什么返回值在屏幕中显示 XML 类型?

java - 我们可以使用 @RequestParam ="CodeTxt"获取 id ("custCode"吗?

java - 来自介绍性程序员的 classcastException : conversion from object to String

java - JPA 2.1 ManyToOne,如果子实体是最后一个实体,则删除子实体(一侧)

java - Spring Security 在休息服务中获取用户信息,用于经过身份验证和未经过身份验证的用户

jsp - .properties或JSP的编码有问题