注解@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();}
通过源码解读,我们可以得到以下结论:
创建三个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");}}
然后启动启动类观察控制台信息输出