Order注解用于排序
public @interface Order { /** * The order value. * <p>Default is {@link Ordered#LOWEST_PRECEDENCE}. * @see Ordered#getOrder() */ int value() default Ordered.LOWEST_PRECEDENCE; }
1.OrderUtils
Spring提供了OrderUtils来获取Class的Order注解排序信息
扩展:Priority注解为javax扩展注解,功能与Order相同
public class OrderUtilsTests { @Test public void getSimpleOrder() { assertEquals(Integer.valueOf(50), OrderUtils.getOrder(SimpleOrder.class, null)); } @Test public void getPriorityOrder() { assertEquals(Integer.valueOf(55), OrderUtils.getOrder(SimplePriority.class, null)); } @Order(50) private static class SimpleOrder {} @Priority(55) private static class SimplePriority {} }
2.Ordered接口
对象排序的另一种实现
public interface Ordered { int getOrder(); }
3.OrderComparator
使用OrderComparator来比较2个对象的排序顺序
public final class OrderComparatorTests { private final OrderComparator comparator = new OrderComparator(); @Test public void compareOrderedInstancesBefore() { assertEquals(-1, this.comparator.compare( new StubOrdered(100), new StubOrdered(2000))); } @Test public void compareOrderedInstancesSame() { assertEquals(0, this.comparator.compare( new StubOrdered(100), new StubOrdered(100))); } @Test public void compareOrderedInstancesAfter() { assertEquals(1, this.comparator.compare( new StubOrdered(982300), new StubOrdered(100))); } private static final class StubOrdered implements Ordered { private final int order; public StubOrdered(int order) { this.order = order; } @Override public int getOrder() { return this.order; } } }
其内部比较逻辑
return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
- i1比i2小则返回-1
- i1比i2大则返回1
- i1等于i2则返回0
4.AnnotationAwareOrderComparator
AnnotationAwareOrderComparator继承自OrderComparator 其可以同时处理对象实现Ordered接口或@Order注解
其提供了静态方法sort,可以对List进行排序
public class AnnotationAwareOrderComparator extends OrderComparator { }
测试代码
public class AnnotationAwareOrderComparatorTests { @Test public void sortInstances() { List<Object> list = new ArrayList<>(); list.add(new B()); list.add(new A()); AnnotationAwareOrderComparator.sort(list); assertTrue(list.get(0) instanceof A); assertTrue(list.get(1) instanceof B); } @Order(1) private static class A { } @Order(2) private static class B { } }
5.Bean注册顺序
Demo2Config的对象将会先于Demo1Config初始化注册
注意点:其构造函数的初始化并不生效
@Configuration @Order(2) public class Demo1Config { public Demo1Config() { System.out.println("Demo1Config"); } @Bean public Demo1Service demo1Service(){ System.out.println("demo1config 加载了"); return new Demo1Service(); } } @Configuration @Order(1) public class Demo2Config { public Demo2Config() { System.out.println("Demo2Config"); } @Bean public Demo2Service demo2Service(){ System.out.println("demo2config 加载了"); return new Demo2Service(); } } public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("core.annotation.order2"); } }
输出的结果信息:
Demo1Config Demo2Config demo2config 加载了 demo1config 加载了
参考
wiselyman.iteye.com/blog/221719…