2016-02-26 99 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; 

} 
相關問題