springboot~AutoConfigureAfter如何控制Bean的注入顺序
  2xk0JyO908yA 17天前 26 0

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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 17天前 0

暂无评论

推荐阅读
  bVJlYTdzny4o   9天前   22   0   0 Java
2xk0JyO908yA