springboot~AutoConfigureAfter如何控制Bean的注入顺序

这个文章主要介绍一下@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在初始化时,使用了正确的可预期的顺序进行注册

posted @ 2024-04-30 13:07  张占岭  阅读(51)  评论(0编辑  收藏  举报