springboot自定义外部扩展文件

在springboot启动的时候调用run方法,可以看到run方法里面的内容,其中有一个getRunListeners方法

 

Ctrl+左键点进这个方法,发现getSpringFactoriesInstances方法,这个方法就是在所有jar包的spring.factories文件中寻找指定类型的值

我们去springboot包里面的spring.factories文件搜索SpringApplicationRunListener

这个类的作用就是把application.yml配置文件中配置的内容加载在项目中,进入这个类可以看到它实现了SpringApplicationRunListener接口。

所以我们也可以创建一个类来实现这个接口,用来加载自己定义的配置文件。

创建一个my.properties,创建一个类MySpringApplicationRunListener类来实现SpringApplicationRunListener

实现里面的方法,在environmentPrepared方法中书写读取配置文件的代码

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        Properties properties = new Properties();
        try {
            //读取my.properties配置文件
            properties.load(this.getClass().getClassLoader().getResourceAsStream("my.properties"));
            //读取名称为my
            PropertySource propertySource = new PropertiesPropertySource("my", properties);
            //将资源添加到springboot项目中
            MutablePropertySources propertySources = environment.getPropertySources();
            propertySources.addLast(propertySource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

然后在resources文件夹下创建一个META-INF文件夹,在里面创建一个spring.factories文件,把springboot包中刚才找到的那个配置copy过来,并且把下面的值改成自己的类路径

我们来创建一个方法测试一下

在my.properties 文件中写了一个键值对 

myName=vhukze

在controller中获取一下

@Value("${myName}")
    private String myName;

    @RequestMapping("/")
    public String getMyName() {
        return myName;
    }

启动项目报错了

这个是报的一个反射异常,没有找到有参构造

再来看一下springboot中的那个EventPublishingRunListener类

这个里面是有一个这样的有参构造的,那我们也在自己的类里面添加一个

现在可以成功启动项目了,访问一下测试方法

 

 

如果想在application.yml配置文件之前加载,可以设置优先级,把我们的MySpringApplicationRunListener类再实现一个Ordered接口,实现里面的getOrder方法,设置返回值小于0,因为加载application配置文件的getOrder方法返回值是0;

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章