SpringBoot Bean加载优先级问题

spring容器载入bean顺序是不确定的,spring框架没有约定特定顺序逻辑规范。但spring保证如果A依赖B(如beanA中有@Autowired B的变量),那么B将先于A被加载。

同一个类中加载顺序

Constructor >> @Autowired >>@ PostConstruct>>@Bean

@DependsOn控制顺序

如果A不依赖B,但是A需要在B后面初始化,可以使用@DependsOn(value=“Bbeanname”)。B的@Bean上面需要手动指定Name,否则找不到。

@Order不能控制顺序

@Order注解并不能改变Bean加载优先级,@Order注解用于设置装载到list中Bean的顺序

@Order(2)
@Component
public class AnoBean1 implements IBean {

    private String name = "ano order bean 1";

    public AnoBean1() {
        System.out.println(name);
    }
}

@Order(1)
@Component
public class AnoBean2 implements IBean {

    private String name = "ano order bean 2";

    public AnoBean2() {
        System.out.println(name);
    }
}

@Component
public class AnoTestBean {

    public AnoTestBean(List<IBean> anoBeanList) {
        for (IBean bean : anoBeanList) {
            System.out.println("in ano testBean: " + bean.getClass().getName());
        }
    }
}

上面代码输出结果
ano order bean 1
ano order bean 2
in ano testBean: AnoBean2
in ano testBean: AnoBean1

你可能感兴趣的:(Spring,spring)