在开发过程我们经常需要用到各种各样的配置文件,用spring读取配置文件的方式网程序员设置一些值是一种比较方便、可扩展性比较好的方法。
但是我们经常会遇到这样一个问题,例如同一个dao的配置文件,可能因为在测试环境,预发布环境,正式环境都需要连接不同的数据库,因此每发布一次就需要修改一次配置,这是比较麻烦的!特别在配置文件比较多的情况下,容易忘记!那么怎么办呢?其实只要将配置文件放在绝对路径下就好了。这样只要第一次发布之后,配置文件不随着项目源码的改变而改变,因为每次读取的都是固定路径的配置,这样各种配置文件是统一维护的,也方便管理。
这样会带来的一个问题就是,因为开发小组成员之间所用的电脑操作系统可能是不同的,window的文件路径是Linux、mac等都是不一样的,window需要C:\\XX,而其他操作系统确实XX/XX这样的形式。所以在读取需要在程序上面稍微变动一下,在读取window系统的时候默认从一个盘加载配置文件。
好了,来看看具体怎么做的吧。。自定义一个类用于读取配置文件,继承PropertiesFactoryBean,并且重写其方法!
/**
* location改为paths
*/
protected String[] paths;
public void setPaths(String[] paths) {
this.paths = paths;
}
public void setFileEncoding(String fileEncoding) {
this.fileEncoding = fileEncoding;
}
protected void loadProperties(Properties props) throws IOException {
if(this.paths != null) {
String[] arr$ = this.paths;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
String path = arr$[i$];
if(this.logger.isInfoEnabled()) {
this.logger.info("Loading properties file from " + path);
}
// 如果是window系统,默认在路径前面加一个c:,从c盘开始读取文件
String os = System.getProperty("os.name");
if(os.toLowerCase().contains("window")) {
path = "C:" + path;
}
FileSystemResource fileSystemResource = new FileSystemResource(path);
try {
//改为用文件流的形式,这样可以从绝对路径读取配置文件
this.fillProperties(props, new EncodedResource(fileSystemResource, this.fileEncoding), this.propertiesPersister);
} catch (IOException var9) {
if(!this.ignoreResourceNotFound) {
throw var9;
}
if(this.logger.isWarnEnabled()) {
this.logger.warn("Could not load properties from " + path + ": " + var9.getMessage());
}
}
}
}
}
void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister) throws IOException {
InputStream stream = null;
Reader reader = null;
try {
String filename = resource.getResource().getFilename();
if(filename != null && filename.endsWith(".xml")) {
stream = resource.getInputStream();
persister.loadFromXml(props, stream);
} else if(resource.requiresReader()) {
reader = resource.getReader();
persister.load(props, reader);
} else {
stream = resource.getInputStream();
persister.load(props, stream);
}
} finally {
if(stream != null) {
stream.close();
}
if(reader != null) {
reader.close();
}
}
}
<bean id="dbResources" class="java.util.ArrayList">
<constructor-arg>
<list>
<value>/data/config/database.properties</value>
</list>
</constructor-arg>
</bean>
<bean id="dbPropertyConfigurer" class="com.example.config.utils.YourPropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="paths" ref="dbResources" />
<property name="fileEncoding" value="utf-8"></property>
</bean>