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

 

springboot如何加载bean springboot如何加载外部插件_spring

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

springboot如何加载bean springboot如何加载外部插件_配置文件_02

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

springboot如何加载bean springboot如何加载外部插件_springboot如何加载bean_03

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

springboot如何加载bean springboot如何加载外部插件_自定义扩展文件_04

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

创建一个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过来,并且把下面的值改成自己的类路径

springboot如何加载bean springboot如何加载外部插件_配置文件_05

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

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

myName=vhukze

在controller中获取一下

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

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

启动项目报错了

springboot如何加载bean springboot如何加载外部插件_配置文件_06

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

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

springboot如何加载bean springboot如何加载外部插件_加载_07

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

springboot如何加载bean springboot如何加载外部插件_spring_08

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

springboot如何加载bean springboot如何加载外部插件_spring_09

 

 

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

 

在高版本的springboot中,我们实现自己的监听器中的environmentPrepared方法,已经不推荐使用了(中划线)

可以看一下我的另一篇博客:sprintboot读取自定义配置文件properties、yml、yaml,环境springboot2.4.4

如果读取ylm或者yaml配置文件也可以看看我上面的这篇博客