Spring注解@Order的使用

2022-11-21 14:39:20

@Order:注解@Order不能决定Spring容器加载Bean的顺序,只能决定执行顺序

1,注解类源码
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})@Documentedpublic @interfaceOrder{/**
	 * The order value.
	 * <p>Default is {@link Ordered#LOWEST_PRECEDENCE}.
	 * @see Ordered#getOrder()
	 */intvalue()default Ordered.LOWEST_PRECEDENCE;}
2,常量类
publicinterfaceOrdered{/**
	 * Useful constant for the highest precedence value.
	 * @see java.lang.Integer#MIN_VALUE
	 */int HIGHEST_PRECEDENCE= Integer.MIN_VALUE;/**
	 * Useful constant for the lowest precedence value.
	 * @see java.lang.Integer#MAX_VALUE
	 */int LOWEST_PRECEDENCE= Integer.MAX_VALUE;intgetOrder();}

注解可以作用在类、方法、字段声明(包括枚举常量);
注解有一个int类型的参数,可以不传,默认是最低优先级;
通过常量类的值我们可以推测参数值越小优先级越高;

3,代码测试
@Configuration(proxyBeanMethods=false)publicclassCatConfig{@Bean@Order(3)public Catcat1(){
        System.err.println("order1------>");returnnewCat("cat1()");}@Bean@Order(2)public Catcat2(){
        System.err.println("order2------>");returnnewCat("cat2()");}@Bean@Order(1)public Catcat3(){
        System.err.println("order3------>");returnnewCat("cat3()");}@Beanpublic CatCat4(List<Cat> cat){
        cat.forEach(s->System.out.println(s.getName()));return cat.get(1);}}

启动项目:
在这里插入图片描述

  • 作者:请我喝杯美式吧
  • 原文链接:https://blog.csdn.net/qq_39513430/article/details/105835724
    更新时间:2022-11-21 14:39:20