最重要的是这一行:OrderUtils.getOrderFromAnnotations(element, annotations),我们进去看看
@Nullable static Integer getOrderFromAnnotations(AnnotatedElement element, MergedAnnotations annotations) { if (!(element instanceof Class)) { return findOrder(annotations); } Object cached = orderCache.get(element); if (cached != null) { return (cached instanceof Integer ? (Integer) cached : null); } Integer result = findOrder(annotations); orderCache.put(element, result != null ? result : NOT_ANNOTATED); return result; } @Nullable private static Integer findOrder(MergedAnnotations annotations) { MergedAnnotation<Order> orderAnnotation = annotations.get(Order.class); if (orderAnnotation.isPresent()) { return orderAnnotation.getInt(MergedAnnotation.VALUE); } MergedAnnotation<?> priorityAnnotation = annotations.get(JAVAX_PRIORITY_ANNOTATION); if (priorityAnnotation.isPresent()) { return priorityAnnotation.getInt(MergedAnnotation.VALUE); } return null; } private static final String JAVAX_PRIORITY_ANNOTATION = "javax.annotation.Priority";两个方法,第一个是简单的缓存,不用看,重点看第二个方法
先判断有没有org.springframework.core.annotation.Order注解
再判断有没有javax.annotation.Priority注解
有注解就去上面的值,没有返回null
回到最开始的方法,进行int值的排序
Integer.compare(i1, i2); public static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); }至此,我们的排序源码就分析完了,我们总结一下:
(1)先判断有没有实现PriorityOrdered,实现PriorityOrdered比没实现的有高优先级
(2)第一步如果比较不出来,判断有没有实现Ordered,如果实现了,取实现方法的int值比较
(3)如果没有实现Ordered,判断有没有org.springframework.core.annotation.Order注解, 有注解,取注解上的order值,进行比较
(4)如果没有Order注解,判断有没有javax.annotation.Priority注解,取注解上的值比较
(5)如果上面都没有,返回Integer.MAX_VALUE,值越大优先级越低