美文网首页
巧用 Spring @Order 进行排序

巧用 Spring @Order 进行排序

作者: 作草分茶 | 来源:发表于2019-12-31 15:53 被阅读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);
    }
    

    相关文章

      网友评论

          本文标题:巧用 Spring @Order 进行排序

          本文链接:https://www.haomeiwen.com/subject/suaboctx.html