咱们在开发的时候使用的是程序内部的配置文件,当咱们部署到测试或者正式环境之后,有些配置须要修改,不能写死,这个时候就须要读取程序外部的配置文件了,程序内部的配置文件就不能继续使用了。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(); } } } } } }