2016-02-26 102 views
0

我正在用java在Spring中编写WebApp后端。在代码中有很多神奇的数字。有没有一种方法可以将此配置放入config中,以便在不重新启动整个应用程序的情况下对此配置中的任何更改生效?如何在spring中动态加载java中的配置

+0

检查此问题http://stackoverflow.com/questions/26150527/how-can-i-reload-properties-file-in-spring-4-using-annotations – user1516873

回答

1

当java进程启动时,加载spring上下文,一旦加载spring上下文,它只会读取属性文件一次,所以如果你改变任何属性,你必须重新启动你的应用程序,这很好。

或者您可以用Apache Commons Configuration项目中的PropertiesConfiguration替换java.util.Properties。它支持自动重新加载,通过检测文件何时更改或通过JMX触发来支持。

另一种替代方法是将所有的prop变量保存在数据库中并定期刷新您的引用缓存,这样您就不必重新启动应用程序,并且可以从数据库实时更改属性。

0

您可以通过下面的步骤调用配置文件:

  1. 使用@Configuration标注为它调用 配置文件中的类。
  2. 另一个注释到类以上声明用于定义路径配置文件@PropertySource({ “URL/PATH_OF_THE_CONFIG_FILE”})
  3. @Value( “$ {PROPERTY_KEY}”)注释上方的变量,其中对应于property_key的值需要被分配。
  4. 下列bean在相同的配置调用类。

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 
         return new PropertySourcesPlaceholderConfigurer(); 
        } 
    
  5. 确保@ComponentScan覆盖了配置文件放在

0

这里就是这样的文件夹,你可以配置它

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemalocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 
    <!--To load properties file --> 
    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="location" value="classpath:META-INF/*-config.properties"> 
    </property></bean>  
    <bean id="createCustomer" class="com.example.Customer"> 
    <property name="propertyToInject" value="${example.propertyNameUnderPropertyFile}"> 
</beans> 

您也可以参考它立即在java文件中

public class Customer { 
@Value("${example.propertyNameUnderPropertyFile}") 
private String attr; 

} 
相关问题