spring bean加载顺序

た 入场券 2022-04-15 04:58 431阅读 0赞

1、使用Spring @DependsOn控制bean加载顺序

该注解用于声明当前bean依赖于另外一个bean。所依赖的bean会被容器确保在当前bean实例化之前被实例化。

1.1 用法

  • 直接或者间接标注在带有@Component注解的类上面。
  • 直接或者间接标注在带有@Bean 注解的方法上面。

使用@DependsOn注解到类层面仅仅在使用component scanning方式时才有效;如果带有@DependsOn注解的类通过XML方式使用,该注解会被忽略,这种方式会生效;

2、java示例

2.1 定义实体类

  1. import javax.annotation.PostConstruct;
  2. /**
  3. * @Title: BeanA.java
  4. * @Package com.spring.pro.bean
  5. * @Description:
  6. * @author ybwei
  7. * @date 2018年11月21日 下午2:56:40
  8. * @version V1.0
  9. */
  10. public class BeanA {
  11. public BeanA(){
  12. System.out.println("A构造方法");
  13. }
  14. @PostConstruct
  15. public void postC(){
  16. System.out.println("A:@PostConstruct");
  17. }
  18. public void init() {
  19. System.out.println("Bean A");
  20. }
  21. }
  22. /**
  23. * @Title: BeanA.java
  24. * @Package com.spring.pro.bean
  25. * @Description:
  26. * @author ybwei
  27. * @date 2018年11月21日 下午2:56:40
  28. * @version V1.0
  29. */
  30. public class BeanB {
  31. public void init() {
  32. System.out.println("Bean B");
  33. }
  34. }

2.2 实例化实体类

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.context.annotation.DependsOn;
  4. import com.spring.pro.bean.BeanA;
  5. import com.spring.pro.bean.BeanB;
  6. /**
  7. * @ClassName: RabbitConfig
  8. * @Description:
  9. * @author weiyb
  10. * @date 2017年12月17日 下午6:08:21
  11. *
  12. */
  13. @Configuration
  14. public class BeanConfig {
  15. /**
  16. * initMethod执行初始化方法
  17. * @DependsOn,必须beanB先被初始化,beanA才会初始化
  18. * @return
  19. * @author ybwei
  20. */
  21. @Bean(name = "beanA", initMethod = "init")
  22. @DependsOn("beanB")
  23. public BeanA myBeanA() {
  24. return new BeanA();
  25. }
  26. @Bean(name = "beanB", initMethod = "init")
  27. public BeanB myBeanB() {
  28. return new BeanB();
  29. }
  30. }

2.3 启动类

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. /**
  4. * @ClassName: ProviderApplication
  5. * @Description:
  6. * @author weiyb
  7. * @date 2017年5月24日 下午2:29:27
  8. */
  9. @SpringBootApplication
  10. public class ProviderApplication {
  11. public static void main(String[] args) {
  12. SpringApplication.run(ProviderApplication.class, args);
  13. }
  14. }

2.4 分析

启动后打印日志

  1. Bean B
  2. A构造方法
  3. A:@PostConstruct
  4. Bean A

因为BeanA需要BeanB先实例化后,才会实例化。

加载顺序:Constructor (构造方法)> @PostConstruct > init-method(bean中的init)

发表评论

表情:
评论列表 (有 0 条评论,431人围观)

还没有评论,来说两句吧...

相关阅读