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

我们在开发的时候使用的是程序内部的配置文件,当我们部署到测试或者正式环境以后,有些配置需要修改,不能写死,这个时候就需要读取程序外部的配置文件了,程序内部的配置文件就不能继续使用了。

下面是我的处理方式,让程序自动读取所需要的文件。比打包的时候把不同环境的配置打在一起要方便。我的处理方式可以满足,修改配置文件后,只要 重启服务即可,不需要重新打包。

欢迎各位提出各种问题批评指正。

<!-- 配置文件,按配置顺序,后面的比前面的优先 -->  
    <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();
                    }
                }
            }
        }

    }
    
}

猜你喜欢

转载自my.oschina.net/u/3770578/blog/1612230
今日推荐