巧用 Spring @Order 进行排序

2019-12-31  本文已影响0人  作草分茶

直接上代码

public class OrderAnnotationTest {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        List<Object> orderList = new ArrayList<>(3);
        orderList.add(a);
        orderList.add(b);
        orderList.add(c);
        orderList.sort(AnnotationAwareOrderComparator.INSTANCE);
        System.out.println(orderList);
    }

    @Order(0)
    static class A {
        @Override
        public String toString() {
            return "A";
        }
    }

    @Order(-1)
    static class B {
        @Override
        public String toString() {
            return "B";
        }
    }

    @Order(2)
    static class C {
        @Override
        public String toString() {
            return "C";
        }
    }
}

结果如下:

[B, A, C]

原理解析:

AnnotationAwareOrderComparator继承自OrderComparator,实际比较的方法如下

private int doCompare(@Nullable Object o1, @Nullable Object o2, @Nullable OrderSourceProvider sourceProvider) {
    boolean p1 = (o1 instanceof PriorityOrdered);
    boolean p2 = (o2 instanceof PriorityOrdered);
    if (p1 && !p2) {
        return -1;
    }
    else if (p2 && !p1) {
        return 1;
    }

    int i1 = getOrder(o1, sourceProvider);
    int i2 = getOrder(o2, sourceProvider);
    return Integer.compare(i1, i2);
}
上一篇下一篇

猜你喜欢

热点阅读