您的位置:首页 > 编程语言 > Java开发

dubbo spring 不同的环境配置多个配置文件

2018-01-24 00:00 190 查看
<!-- 配置文件,按配置顺序,后面的比前面的优先 -->
<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}读取配置项,

在java里在属性的set方法上面用@Value(value="${jdbc.master.user}") 就可以了。

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();
}
}
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: