properties文件之间的变量引用【springboot】

1 引言: 

项目重构,单体项目转成微服务架构,然一些生产properties配置要定义在环境变量启动,并且由于一些properties文件是私有引用

不得不涉及到properties变量引用问题;

1 如果封装私有代码通过配置文件交给sping加载@Value("com.id")引用,然 很简单, 只要 在环境变量定义对应的

spring.datasource.url=${spring.datasource.url}
spring.datasource.username=${spring.datasource.username}

spring.datasource.url=localhost:3306:test..

spring.datasource.user=root....

只要这样就好了;

然而,有些私有的会通过

InputStream ins = this.class.getResourceAsStream("classpath*:a.properties");;
InputStreamReader in = new InputStreamReader(ins, "utf-8");
 prop.load(in);
 String serverUrl = prop.getProperty("URL");
 String sysId = prop.getProperty("Id");
 String pwd = prop.getProperty("pwd");
......

上面直接写在环境变量里面就不能生效了,

总是报${com.url}读取不到;

java.io.FileNotFoundException: ${com.path1} (系统找不到指定的文件。)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:93)

就要换一种思路了,  这样我们必须要重写对应的a.properties文件了

以springboot演示举例说明:


@Configuration
public class MyConfigurer implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver;
    static final Log log = LogFactory.getLog(MyConfigurer.class);

    @Override
    public void setEnvironment(Environment env) {
        //绑定并读取对应properties文件的值
        propertyResolver = new RelaxedPropertyResolver(env);

        Properties prop = new Properties();
        FileOutputStream oFile=null;

        try {

            oFile =new FileOutputStream(this.getClass().getResource("/").getPath()+"/a.properties",false);//true表示追加打开

            prop.setProperty("url",  propertyResolver.getProperty("com.url"));
            prop.setProperty("id", propertyResolver.getProperty("com.id"));
            prop.setProperty("pwd", propertyResolver.getProperty("com.pwd"));
            ###重写a.proerties文件
            prop.store(new OutputStreamWriter(oFile, "utf-8"), "The New properties file");
            log.info("重写a.properties文件完毕");

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(oFile!=null){
                    oFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

这样,私有的jar里面的就可以读取到了 

发布了48 篇原创文章 · 获赞 7 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/maguoliang110/article/details/98536899
今日推荐