【问题标题】:Spring Reload Property - Bean not updatedSpring Reload 属性 - Bean 未更新
【发布时间】:2017-11-24 16:06:08
【问题描述】:

我有一个 web 服务,它通过 spring 从位于服务器中的 application.properties 文件中获取属性,例如 query[testSql]

public class RuntimeEnvironmentPropertiesConfigurerextends PropertyPlaceholderConfigurer
        implements InitializingBean, RuntimeEnvironmentInterface

现在该查询已注入到我的 Spring bean dao 中。

<bean id="dao" name="dao" class="com.dao.DaoImpl">
  <property name="ackJdbcTemplate"  ref="ackJdbcTemplate" />  
  <property name="testSql" value="${dao.query.tSql}" />
 </bean>

How can I reload properties file in Spring 4 using annotations? 链接的帮助下,我可以在运行时重新加载该属性。 验证人

@Autowired
public RuntimeEnvironmentInterface propertyLoader;

....

  Set s=propertyLoader.getProperties();
        Iterator itr=s.iterator();
        while(itr.hasNext()){
        String tempKey=String.valueOf(itr.next());
        logger.info(tempKey +"==="+propertyLoader.getProperty(tempKey));

但问题是我的 dao bean 不接受更新的 testSql 查询。它在旧的上运行,直到我重新启动应用程序。

我在单独的 url 映射中找到了一种方法,我写了一个方法来完成以下工作:

Dao.setTestSql(propertyLoader.getProperty("com.dao.query.tSql"));

更新属性的人必须在更新属性后点击 url。

但是我必须为所有 bean 和注入的财产做这件事。这是一项非常忙碌的工作。我错过了一个财产,我注定要失败。 有没有其他方法可以自动更新注入的 bean?我需要在不重启的情况下反映我更新的属性。

我试图理解给出的 wuenschenswert 代码但无法理解。

【问题讨论】:

  • 为什么不在你的 DAO 中使用 propertyLoader?
  • @Alexey Soshin 谢谢你的建议,但整个应用程序中有超过 12 个 bean 并且有很多属性,所以我正在寻找重新加载所有属性的方法,而不必去每个 Spring bean 和设置属性。

标签: java spring properties spring-bean


【解决方案1】:
<property name="testSql" value="${dao.query.tSql}" />

这意味着在 bean 初始化时 Spring 使用名为 dao.query.tSql 的属性计算属性值。所以setTestSql() 方法会在上下文初始化时被调用,仅此而已。当你的属性被重新加载时,属性加载器不会推送新的属性值到你的 bean 中。

但是,正如 Alexey 所建议的,您可以在每次执行这样的 sql 查询时从propertyLoader提取属性值:

final String actualQuery = propertyLoader.getProperty("com.dao.query.tSql");
executeQuery(actualQuery);

有一个问题:当属性数量增加时,这可能会开始看起来很难看。但是,如果您创建一些封装这些访问的类,则可以缓解这种情况;该类将通过其方法提供属性。示例:

public class DynamicProperties {
    private final RuntimeEnvironmentInterface propertyLoader;

    public DynamicProperties(RuntimeEnvironmentInterface propertyLoader) {
        this.propertyLoader = propertyLoader;
    }

    public String tSql() {
        return propertyLoader.getProperty("dao.query.tSql");
    }

    ... other methods for other properties
}

然后在你的Dao中创建这个类的一个实例:

private DynamicProperties dynamicProperties = new DynamicProperties(propertyLoader);

然后

executeQuery(dynamicProperties.tSql());

一点好处:您可以在同一个 DynamicProperties 类中进行类型转换(例如,当您的属性是 int 而不是 String 时)。

【讨论】:

  • @Roman关于包装器的想法很酷!!!但是整个应用程序中有超过 12 个 bean,并且这些 bean 中注入了很多属性,所以我正在寻找重新加载所有属性的方法,而不必去每个 Spring bean 和设置属性。因此,将来他们会添加删除或更新任何 bean 定义,无需更改方法。该方法将从文件中重新加载所有属性,并在使用时更新属性。
猜你喜欢
  • 2012-02-04
  • 2021-11-02
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多