咱們在開發的時候使用的是程序內部的配置文件,當咱們部署到測試或者正式環境之後,有些配置須要修改,不能寫死,這個時候就須要讀取程序外部的配置文件了,程序內部的配置文件就不能繼續使用了。java
下面是個人處理方式,讓程序自動讀取所須要的文件。比打包的時候把不一樣環境的配置打在一塊兒要方便。個人處理方式能夠知足,修改配置文件後,只要 重啓服務便可,不須要從新打包。spring
歡迎各位提出各類問題批評指正。ide
<!-- 配置文件,按配置順序,後面的比前面的優先 --> <bean id="myConfig" class="com.***.common.util.MyConfigPropertyPlaceholder"> <property name="locations"> <list> <value>classpath:dubbo.properties</value> <value>file:/home/config/user/dubbo.properties</value> <value>file:D:\config\user\dubbo.properties</value> </list> </property> </bean>
本身寫的類繼承自PropertyPlaceholderConfigurer,讀取多個配置文件的時候,即便文件不存在也不會報錯。不影響程序啓動。測試
在xml裏用${jdbc.master.user}讀取配置項, this
在java裏在屬性的set方法上面用@Value(value="${jdbc.master.user}") 就能夠了。spa
import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.core.io.Resource; import org.springframework.util.DefaultPropertiesPersister; import org.springframework.util.PropertiesPersister; public class MyConfigPropertyPlaceholder extends PropertyPlaceholderConfigurer{ private Logger logger = LoggerFactory.getLogger(getClass()); protected Properties[] localProperties; protected boolean localOverride = false; private Resource[] locations; private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister(); public void setLocations(Resource[] locations) { this.locations = locations; } public void setLocalOverride(boolean localOverride) { this.localOverride = localOverride; } protected void loadProperties(Properties props) throws IOException { if (locations != null) { for (Resource location : this.locations) { InputStream is = null; try { is = location.getInputStream(); this.propertiesPersister.load(props, is); logger.info("讀取配置文件{}成功",location); } catch (IOException ex) { logger.info("讀取配置文件{}失敗.....",location); } finally { if (is != null) { is.close(); } } } } } }