您好,欢迎来到独旅网。
搜索
您的当前位置:首页Spring @Order注解详解

Spring @Order注解详解

来源:独旅网

源码

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {

	/**
	 * The order value.
	 * <p>Default is {@link Ordered#LOWEST_PRECEDENCE}.
	 * @see Ordered#getOrder()
	 */
	int value() default Ordered.LOWEST_PRECEDENCE;

}
public interface Ordered {

	/**
	 * 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
	 */
	int getOrder();

}

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

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

案例

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

@Component
@Order(1)
public class Cat1 {
    public Cat1() {
        System.out.println("Order:1");
    }
}

@Component
@Order(2)
public class Cat2 {
    public Cat2() {
        System.out.println("Order:2");
    }
}

@Component
@Order(3)
public class Cat3 {
    public Cat3() {
        System.out.println("Order:3");
    }
}

然后启动启动类观察控制台信息输出

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- dcrkj.com 版权所有 赣ICP备2024042791号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务