2017-06-21 73 views
1

我有过春天春天刷新物业 - 比恩不更新

public class RuntimeEnvironmentPropertiesConfigurerextends PropertyPlaceholderConfigurer 
     implements InitializingBean, RuntimeEnvironmentInterface 

现在查询是在我的Spring bean的DAO注入获取从位于象查询[testSql]服务器application.properties文件属性web服务。

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

验证,但问题是我的道Bean不承担更新testSql query.It运行在旧的,直到我重新启动应用程序。

我发现像独立URL映射的方法我写了下面做工作的方法:

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

,谁更新,她在更新的属性后,打的网址。

但是,我必须为所有的豆和注入的财产做。这是非常忙碌的工作。我想念一个属性,我注定要失败。 是否有任何其他方式来自动更新注入的bean?我需要我的更新属性反映而不重新启动。

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

+1

为什么不在你的DAO中使用propertyLoader? –

+0

@Alexey Soshin谢谢你的建议,但总的应用程序中有超过12个bean,并且有很多属性,所以我正在寻找重新装入所有属性的方法,而不必去每个Spring bean和设置属性。 – juneSakura

回答

2
<property name="testSql" value="${dao.query.tSql}" /> 

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

但是,正如阿列克谢建议,你可以从您的每一次propertyLoader属性值执行一个SQL查询是这样的:

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

+0

@罗曼这个包装很酷的想法!我但是在总的应用程序中有超过12个bean,并且在这些bean中注入了很多属性,所以我正在寻找重新加载所有属性的方法,而不必去每个Spring bean并设置属性。所以在将来他们会添加删除或更新任何bean定义,不需要改变方法。该方法将实时从文件中实时载入所有属性,并在每次使用属性时更新属性。 – juneSakura