Spring Boot的加载顺序
Spring Boot的加载顺序是一个复杂的话题,它涉及到Spring Boot的自动配置、Bean的创建顺序、配置文件的加载等多个方面。理解这些加载顺序对于我们优化Spring Boot应用的启动时间和行为至关重要。
一、Spring Boot自动配置的加载顺序
Spring Boot的自动配置是通过@EnableAutoConfiguration或@SpringBootApplication注解来实现的。Spring Boot在启动时会根据类路径下的 jar 包依赖为项目进行自动配置。
- 默认配置:Spring Boot框架本身带有一系列默认配置,这些默认配置是在Spring Boot的代码中硬编码的。
application.properties/application.yml文件:在classpath根目录下的这些文件是最常用的配置文件,它们会被自动加载,并且其中的配置项会覆盖默认配置。- 特定profile相关的配置文件:如果指定了profile,那么Spring Boot会加载
application-{profile}.properties或application-{profile}.yml文件中的配置,这些配置会覆盖上述两种文件中的配置。
二、Bean的创建顺序
控制Spring Boot中Bean的加载顺序可以通过以下几种方式:
1. @DependsOn
@DependsOn注解可以用来控制bean的创建顺序,该注解用于声明当前bean依赖于另外一个bean。所依赖的bean会被容器确保在当前bean实例化之前被实例化。
代码示例:
@Configuration
public class BeanOrderConfiguration {
@Bean
@DependsOn("beanB")
public BeanA beanA(){
System.out.println("bean A init");
return new BeanA();
}
@Bean
public BeanB beanB(){
System.out.println("bean B init");
return new BeanB();
}
}
以上代码bean的加载顺序为:bean B init -> bean A init。
2. 参数注入
在@Bean标注的方法上,如果你传入了参数,springboot会自动会为这个参数在spring上下文中寻找这个类型的引用,并先初始化这个类的实例。
代码示例:
@Bean
public BeanA beanA(BeanB demoB){
System.out.println("bean A init");
return new BeanA();
}
@Bean
public BeanB beanB(){
System.out.println("bean B init");
return new BeanB();
}
以上结果,beanB先于beanA被初始化加载。
3. 利用bean的生命周期中的扩展点
在spring体系中,从容器到Bean实例化&初始化都是有生命周期的,并且提供了很多的扩展点,允许你在这些步骤时进行逻辑的扩展。
4. @AutoConfigureOrder
这个注解用来指定配置文件的加载顺序。但需要注意的是,@AutoConfigureOrder注解在实际测试中发现,对于单个Bean之间的顺序控制并不生效。
三、配置文件的加载顺序
Spring Boot配置文件的加载顺序如下:
application.properties:首先加载application.properties文件中的配置。application.yml:然后加载application.yml文件中的配置,其配置会覆盖application.properties中的配置。- 特定profile的配置文件:如果有激活的profile,那么会加载
application-{profile}.properties或application-{profile}.yml文件中的配置,这些配置会覆盖上述文件中的配置。
四、总结
理解Spring Boot的加载顺序对于我们优化应用的启动时间和行为至关重要。通过合理利用@DependsOn、参数注入、生命周期扩展点等方式,我们可以控制Bean的加载顺序。同时,了解配置文件的加载顺序可以帮助我们更好地管理应用的配置。这些知识对于Spring Boot开发者来说是非常宝贵的。