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里面的就可以读取到了 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值