Spring @Order注解详解

2022年11月23日09:59:44

注解@Order的作用是定义Spring容器加载Bean的顺序。

源码

@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()defaultOrdered.LOWEST_PRECEDENCE;}
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;/**
	 * Get the order value of this object.
	 * <p>Higher values are interpreted as lower priority. As a consequence,
	 * the object with the lowest value has the highest priority (somewhat
	 * analogous to Servlet {@code load-on-startup} values).
	 * <p>Same order values will result in arbitrary sort positions for the
	 * affected objects.
	 * @return the order value
	 * @see #HIGHEST_PRECEDENCE
	 * @see #LOWEST_PRECEDENCE
	 */intgetOrder();}

通过源码解读,我们可以得到以下结论:

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

案例

创建三个pojo类Cat1, Cat2, Cat3,使用@Component注解将其交给Spring容器自动加载,每个类分别加上@Order(1), @Order(2), @Order(3)注解。

@Component@Order(1)publicclassCat1{publicCat1(){System.out.println("Order:1");}}@Component@Order(2)publicclassCat2{publicCat2(){System.out.println("Order:2");}}@Component@Order(3)publicclassCat3{publicCat3(){System.out.println("Order:3");}}

然后启动启动类观察控制台信息输出
Spring @Order注解详解

  • 作者:心潮的滴滴
  • 原文链接:https://blog.csdn.net/qq_42582773/article/details/123703186
    更新时间:2022年11月23日09:59:44 ,共 1369 字。