前言
本章节深入讲解spring的comparator,使用与细节,帮助大家在项目里面正确使用comparator。源码解读无法通过文字很详细的解释,诠释。需要读者多次阅读,深入理解,组织逻辑,大脑慢慢形成整个流程。
从深入理解java api中的comparator,在脑海中形成一个技术蓝图
private Comparatorcomparator = new Comparator () { @Override public int compare(Integer o1, Integer o2) { if(o1 == o2){ return 0; } return o1 > o2?1:-1; } };public void comparatorTest(){ Random random = new Random(); List intList = new ArrayList<>(); for(int i = 0 ; i< 20 ; i++){ intList.add(random.nextInt(40)); } log.info("intList里面的数据,现在是无序的:" + intList); Collections.sort(intList, comparator); log.info("排序之后的结果:" + intList.toString());}
结果
2018-04-01 11:27:44.455 [main] INFO c.n.b.spring.core.ordere.OrdereTest - intList里面的数据,现在是无序的:[26, 21, 18, 35, 25, 14, 15, 17, 15, 13, 37, 15, 35, 29, 13, 19, 32, 15, 19, 12]2018-04-01 11:27:44.479 [main] INFO c.n.b.spring.core.ordere.OrdereTest - 排序之后的结果:[12, 13, 13, 14, 15, 15, 15, 15, 17, 18, 19, 19, 21, 25, 26, 29, 32, 35, 35, 37]
- 需要comparator的实现类
- 实例化comparator的子类
- 保存实例化结果
- 调用Collections.sort(intList, comparator);触发排序
流程分析
按照上面comparator的流程,在spring中寻找对应的流程。
需要comparator的实现类,与基本体系
spring 里面comparator的有两个子类分别是OrderComparator,AnnotationAwareOrderComparator
实例化comparator的子类
comparator的子类都会在当前类里面声明一个该类的静态不可变的变量
public class OrderComparator implements Comparator
public class AnnotationAwareOrderComparator extends OrderComparator { public static final AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator();}
保存实例化结果
在DefaultListableBeanFactory里面声明了一个Comparator类型的dependencyComparator变量,用于对bean进行排序
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable { /** Optional OrderComparator for dependency Lists and arrays */ private Comparator
一旦使用AnnotatedBeanDefinitionReader与ClassPathBeanDefinitionScanner,就会加载AnnotationAwareOrderComparator
public class AnnotationConfigUtils { public static SetregisterAnnotationConfigProcessors( BeanDefinitionRegistry registry, Object source) { DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } } ..... }}
调用Collections.sort(intList, comparator)触发排序
对BeanFactoryPostProcessor及子类的list接口进行排序
class PostProcessorRegistrationDelegate { private static void sortPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) { Comparator
在调用getBean,如果是返回结果是List或者是Array.就会进行排序
private Object resolveMultipleBeans(DependencyDescriptor descriptor, String beanName, SetautowiredBeanNames, TypeConverter typeConverter) { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); Map matchingBeans = findAutowireCandidates(beanName, componentType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof Object[]) { Arrays.sort((Object[]) result, adaptDependencyComparator(matchingBeans));//这里会进行排序 } return result; } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { Class elementType = descriptor.getCollectionType(); if (elementType == null) { return null; } Map matchingBeans = findAutowireCandidates(beanName, elementType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof List) { Collections.sort((List ) result, adaptDependencyComparator(matchingBeans));//这里会进行排序 } return result; } else if (Map.class.isAssignableFrom(type) && type.isInterface()) { } else { return null; } }
comparator分析
OrderComparator的实现非常简单,按照compare--> doCompare --> getOrder(Object , OrderSourceProvider)--> getOrder(Object )-->findOrder() 循序查看就好了
OrderComparator核心代码
public class OrderComparator implements Comparator
AnnotationAwareOrderComparator核心代码
public class AnnotationAwareOrderComparator extends OrderComparator { public static final AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator(); protected Integer findOrder(Object obj) { // 调用OrderComparator.findOrder,先识别Ordered接口, Integer order = super.findOrder(obj); if (order != null) { return order; } // 检查@Order和@Priority各种元素 // Method,AnnotatedElement的对象只会识别@Order if (obj instanceof Class) { return OrderUtils.getOrder((Class ) obj); } else if (obj instanceof Method) { Order ann = AnnotationUtils.findAnnotation((Method) obj, Order.class); if (ann != null) { return ann.value(); } } else if (obj instanceof AnnotatedElement) { 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; } 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; }}
OrderUtils
OrderUtils 很简单负责从class中识别 @Priority 与 @Order注解
public abstract class OrderUtils { private static Class priorityAnnotationType = null; static { try { // 加载 @Priority 注解, priorityAnnotationType = (Class ) ClassUtils.forName("javax.annotation.Priority", OrderUtils.class.getClassLoader()); } catch (Throwable ex) { // javax.annotation.Priority not available, or present but not loadable (on JDK 6) } } public static Integer getOrder(Class type) { return getOrder(type, null); } public static Integer getOrder(Class type, Integer defaultOrder) { // @Order 优于 @Priority 识别 Order order = AnnotationUtils.findAnnotation(type, Order.class); if (order != null) { return order.value(); } // 识别 @Priority 注释 Integer priorityOrder = getPriority(type); if (priorityOrder != null) { return priorityOrder; } return defaultOrder; } public static Integer getPriority(Class type) { if (priorityAnnotationType != null) { Annotation priority = AnnotationUtils.findAnnotation(type, priorityAnnotationType); if (priority != null) { return (Integer) AnnotationUtils.getValue(priority); } } return null; }}
总结
Ordered相关对象总结
- 默认具有以下接口与注解的类才会进行排序
- PriorityOrdered
- Ordered
- @Priority
- OrderComparator负责PriorityOrdered,Ordered
- AnnotationAwareOrderComparator负责, @Priority
- AnnotationAwareOrderComparator只会在xml开启action扫描或者使用 AnnotatedBeanDefinitionReader与ClassPathBeanDefinitionScanner,才会加载
只会对同类型的对象进行排序
- 对BeanFactoryPostProcessor,及子类进行排序
- 在调用getBean,如果是返回结果是List或者是Array.就会进行排序
- ConfigurationClassParser.processDeferredImportSelectors 对@Impor排序
- AspectJ 也就是aop
识别优先级
同时存在多个排序实现方式,哪个方式的值作为排序的值。Ordered优选级比@Order,@Order优选级@Priority高
@Order(value = -10000)@Priority ( value = 0 )public class OrderType implements Ordered{ @Override public int getOrder( ) { return 10000; }}
上面的代码,如何通过AnnotationAwareOrderComparato.findOrde()得到的值是10000,如果没有实现Ordered接口,得到是值是-1000
排序优先级
@Test public void orderTypeTest(){ Listlist = new ArrayList< Ordered >(); list.add( new OrderType( ) ); list.add( new PriorityOrderedType() ); Collections.sort(list , AnnotationAwareOrderComparator.INSTANCE); System.out.println( list ); } public class OrderType implements Ordered{ @Override public int getOrder( ) { return -1; } public String toString(){ return "Ordered"; } } public class PriorityOrderedType implements PriorityOrdered{ @Override public int getOrder( ) { return 10000; } public String toString(){ return "PriorityOrderedType"; } }[PriorityOrderedType, Ordered]
从上面的代码,与结果会发现,PriorityOrdered的实现类order值是10000,而Ordered的实现类order值是-10000,理论上来说输出结果是[Ordered , PriorityOrderedType],为什么出现这种情况。因为PriorityOrdered接口排序优选Ordered接口(包括@Order, @Priority)