spring之OrderComparator

OrderComparator是Spring所提供的一种比较器,可以用来根据@Order注解或实现Ordered接口来执行值进行笔记,从而可以进行排序。

OrderComparator用法

import org.springframework.core.Ordered;

public class A implements Ordered {

    @Override
    public int getOrder() {
        return 3;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
import org.springframework.core.Ordered;

public class B implements Ordered {

    @Override
    public int getOrder() {
        return 1000;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
    public static void main(String[] args) {
        A a = new A();
        B b = new B();

        OrderComparator comparator = new OrderComparator();
        System.out.println(comparator.compare(a, b));

        List list = new ArrayList<>();
        list.add(a);
        list.add(b);

        // 按order值升序排序
        list.sort(comparator);

        System.out.println(list);
    }

AnnotationAwareOrderComparator用法

AnnotationAwareOrderComparator是OrderComparator的子类,它支持用@Order来指定order值。

import org.springframework.core.annotation.Order;

@Order(302)
public class C {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
import org.springframework.core.annotation.Order;

@Order(301)
public class D {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
    public static void main(String[] args) {
        C c = new C();
        D d = new D();

        AnnotationAwareOrderComparator comparator = new AnnotationAwareOrderComparator();
        System.out.println(comparator.compare(c, d));

        List list = new ArrayList<>();
        list.add(c);
        list.add(d);

        // 按order值升序排序
        list.sort(comparator);

        System.out.println(list);
    }

疑问

当同时使用Ordered接口和注解 @Order时,两者的排序是按照什么实现的?

在AnnotationAwareOrderComparator的源码中有解释。

	/**
	 * This implementation checks for {@link Order @Order} or
	 * {@link javax.annotation.Priority @Priority} on various kinds of
	 * elements, in addition to the {@link org.springframework.core.Ordered}
	 * check in the superclass.
	 */
	@Override
	@Nullable
	protected Integer findOrder(Object obj) {
		// 先拿实现接口的值
		Integer order = super.findOrder(obj);
		// 如果不为空则直接返回
		if (order != null) {
			return order;
		}
		// 为空时,则返回注解上面的值
		return findOrderFromAnnotation(obj);
	}

	@Nullable
	private Integer findOrderFromAnnotation(Object obj) {
		AnnotatedElement element = (obj instanceof AnnotatedElement ? (AnnotatedElement) obj : obj.getClass());
		MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY);
		Integer order = OrderUtils.getOrderFromAnnotations(element, annotations);
		if (order == null && obj instanceof DecoratingProxy) {
			return findOrderFromAnnotation(((DecoratingProxy) obj).getDecoratedClass());
		}
		return order;
	}

你可能感兴趣的:(#,spring,spring,java,后端)