为什么要加载外部配置?

最近也是很头疼,我们有开发环境,测试环境,生产环境,生产又分为内网部署环境,外网测试环境,然后更头疼的是,每个人部署的地方还不一样,内网部署环境的redis和mysql又在内网的其他节点上。于是我的代码就写了好多个不同的方法,通过调用不同的方法,进行使用,但是这样每次修改我都需要重新编译,打包,提交,很麻烦。

于是采用加载外部配置的方式,我只需要注释掉,我不需要的,然后重新运行一下,他就会自动赌气这个外部配置,这样就省去了注释修改代码、编译、打包的问题。而且以后换机器了,只用在配置文件上改一下就行。

如何进行外部配置?

大家一般都会用log4j,log4j有一个properties文件,对日志进行控制,避免日志无限扩大,导致磁盘被写满。springBoot也有一个properties,里面会默认

所以说,我们本次也使用properties文件(外置的方式)

1.在项目目录创建一个config的文件夹

springboot 加载jar包中的dll springboot加载外部jar_jar

2.在config中创建一个properties文件

我创建一个叫db.properties的文件,咱们用redis做测试。

内容如下:我为了见名知意,才叫redis.ip其实这些都是随便写

#redis测试 redis.ip = 192.168.9.101 redis.auth = mima

3.写一个类用来定义properties的位置

类中代码如下:

public static Properties DBproperties=new Properties();
public static void loadDbProperties(){
    FileInputStream fileInputStream = null;
    try {
        //定义路径,这里是相对路径,绝对路径也可以的
        fileInputStream = new FileInputStream("config/db.properties");
        DBproperties.load(fileInputStream);

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

4.在需要运行的类中加载

在springBoot中推荐SpringApplication中加载,如果是脚本文件,则在必被运行的脚本上加载,最好是第一行,越早执行,其他的类越早能使用。

InitLogRecord.loadDbProperties();//获取properties
Properties dBproperties = DBproperties;//现在可以在任何地方,直接调用了

springboot 加载jar包中的dll springboot加载外部jar_spring boot_02

 

 5、在需要读取配置的地方引入

redis加载的方法

public static Jedis getLiveJedis(){
    try {
        System.out.println("redis中"+DBproperties.get("redis.ip").toString());
        Jedis jedis = new Jedis(DBproperties.get("redis.ip").toString());
        jedis.auth(DBproperties.get("redis.auth").toString());
        return jedis;
    }catch (Exception  e){
        return null;
    }

}

6.测试

调用,成功,在主类中初始化后,在子方法中引入全局变量,子方法成功获取到具体内容。

springboot 加载jar包中的dll springboot加载外部jar_加载_03

 

 

springboot 加载jar包中的dll springboot加载外部jar_redis_04