这个文章主要介绍一下@AutoConfigureAfter在spring框架中的作用,在使用过程中,很多开辟人员在使用它的时间都出现了题目,题目比较多的就是它们的注册顺序总不是我们预期的,下面介绍一下正常的使用方法。
- @AutoConfigureAfter用在配置类上面,即需要在@Configuration修饰的类上,而不是@Component上面。
- 这些配置类,需要在spring.factories上面进行注册
- @AutoConfigureAfter影响的是配置类中@Bean声明的方法,而不是配置类本身
代码测试
祖父配置- @Configuration
- @AutoConfigureBefore(Father.class) // 在我儿子Father之前,我GrandFather先初始化
- public class GrandFather {
- @Bean
- public String grandFatherBean() {
- System.out.println("配置類GrandFatherConfig構造器被執行...");
- return null;
- }
- }
复制代码 父亲配置- @Configuration
- public class Father {
- @Bean
- public String fatherTest() {
- System.out.println("配置類FatherConfig構造器被執行");
- return "配置類FatherConfig構造器被執行...";
- }
- }
复制代码 儿子配置- @Configuration
- @AutoConfigureAfter(Father.class) // 在爸爸之初始化
- public class Son {
- @Bean
- public String SonBean() {
- System.out.println("配置類SonConfig構造器被執行...");
- return null;
- }
- }
复制代码 spring.factories配置相关- org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
- com.lind.common.bean.family.Father,\
- com.lind.common.bean.family.GrandFather,\
- com.lind.common.bean.family.Son
复制代码 springboot启动后,可以看到截,这些bean在初始化时,使用了正确的可预期的顺序进行注册
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |