项目中的配置文件多越来越多,集群环境也越来越多,方便配置统一管理,可以把配置文件存放到数据库表中,
可以选择使用Apache的commons-configuration工具读取数据库中的配置文件,但是它会每次都去加载数据库,个人觉得没必要浪费资源.
Properties本来就是不常修改的。故自己实现加载本地主要配置文件和数据库配置文件。继承PreferencesPlaceholderConfigurer类,重写mergeProperties()方法;
代码和配置如下:
<!--自己写个实现加载DB配置文件的 DatabaseProperties类 继承PreferencesPlaceholderConfigurer-->
<bean id="configProperties" class="com.fooduo.sys.utils.dbproper.DatabaseProperties">
<property name="locations">
<list>
<value>classpath:/properties/jdbc.properties</value>
</list>
</property>
<property name="query" >
<value>select key_,value_ from T_CONFIGURATION where status > 0</value>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>
代码片段如下
// 查询配置的SQL语句,通过上面的配置注入
private String query;
//重新PropertiesLoaderSupport解析本地配置文件的方法mergeProperties
@Override
protected Properties mergeProperties() throws IOException {
Properties result = new Properties();
if (this.localOverride) {
loadProperties(result);
}
if (this.localProperties != null) {
for (Properties localProp : this.localProperties) {
CollectionUtils.mergePropertiesIntoMap(localProp, result);
}
}
if (!(this.localOverride)) {
loadProperties(result);
}
//解析完成后 开始读取数据库配置文件
//用connection 因为DataSource通过properties加载配置完成后才能注入!
Connection connection = null;
try {
//result为最终Spring全部加载的properties,所有可以直接取到数据库的配置
Class.forName(result.getProperty("master.driverClassName"));
connection = DriverManager.getConnection(result.getProperty("master.url"), result.getProperty("master.username"), result.getProperty("master.password"));
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String key = rs.getString(1);
String value = rs.getString(2);
if (!StringUtils.isBlank(key) && !StringUtils.isBlank(value)) {
result.setProperty(key, value);
}
}
rs.close();
ps.close();
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
return result;
}
完成!!!!
如果需要在Controller里使用注解@Value加载配置文件需要在DispatcherServlet容器再次加载上面的配置
@Value("${master.username}")
private String username;