1. 程式人生 > >Spring原始碼:AnnotationAwareOrderComparator

Spring原始碼:AnnotationAwareOrderComparator

AnnotationAwareOrderComparator簡介:

AnnotationAwareOrderComparator是OrderComparator的子類,用來支援Spring的Ordered類、@Order註解和@Priority註解。

原始碼解析

public class AnnotationAwareOrderComparator extends OrderComparator {
    // 對外提供的共享例項
	public static final AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator
(); /** * 用來檢查實現Ordered介面、@Order和@Priority註解 */ protected Integer findOrder(Object obj) { // 檢查常規的Ordered介面,通過子類重寫的getOrder方法返回順序值 Integer order = super.findOrder(obj); if (order != null) { return order; } // 檢查實現@Order和@Priority註解 if (obj instanceof Class) { // 在類上檢查@Order和@Priority註解,並找出順序值
return OrderUtils.getOrder((Class<?>) obj); } else if (obj instanceof Method) { // 在方法上檢查@Order註解,並找出順序值 Order ann = AnnotationUtils.findAnnotation((Method) obj, Order.class); if (ann != null) { return ann.value(); } } else if (obj instanceof AnnotatedElement) { // 在註解中找@Order註解,並找出順序值
Order ann = AnnotationUtils.getAnnotation((AnnotatedElement) obj, Order.class); if (ann != null) { return ann.value(); } } else if (obj != null) { order = OrderUtils.getOrder(obj.getClass()); if (order == null && obj instanceof DecoratingProxy) { order = OrderUtils.getOrder(((DecoratingProxy) obj).getDecoratedClass()); } } return order; } /** * 找Priority值 */ public Integer getPriority(Object obj) { Integer priority = null; if (obj instanceof Class) { priority = OrderUtils.getPriority((Class<?>) obj); } else if (obj != null) { priority = OrderUtils.getPriority(obj.getClass()); if (priority == null && obj instanceof DecoratingProxy) { priority = OrderUtils.getOrder(((DecoratingProxy) obj).getDecoratedClass()); } } return priority; } public static void sort(List<?> list) { if (list.size() > 1) { Collections.sort(list, INSTANCE); } } public static void sort(Object[] array) { if (array.length > 1) { Arrays.sort(array, INSTANCE); } } public static void sortIfNecessary(Object value) { if (value instanceof Object[]) { sort((Object[]) value); } else if (value instanceof List) { sort((List<?>) value); } } }