SpringBoot源码阅读(5)——AnnotationAwareOrderComparator排序

SpringBoot中工厂类加载器加载的实现类通常有多个,这些类通常会排序后放入集合
AnnotationAwareOrderComparator是常用的比较器

AnnotationAwareOrderComparator

父类:OrderComparator
接口:Comparator

相关方法

public static void sort(Object[] array) {
	if (array.length > 1) {
		Arrays.sort(array, INSTANCE);
	}
}
@Override
public int compare(@Nullable Object o1, @Nullable Object o2) {
	return doCompare(o1, o2, null);
}
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);
}
private int getOrder(@Nullable Object obj, @Nullable OrderSourceProvider sourceProvider) {
	Integer order = null;
	if (obj != null && sourceProvider != null) {
		Object orderSource = sourceProvider.getOrderSource(obj);
		if (orderSource != null) {
			if (orderSource.getClass().isArray()) {
				for (Object source : ObjectUtils.toObjectArray(orderSource)) {
					order = findOrder(source);
					if (order != null) {
						break;
					}
				}
			}
			else {
				order = findOrder(orderSource);
			}
		}
	}
	return (order != null ? order : getOrder(obj));
}

排序逻辑:

  1. 先看是否实现了接口PriorityOrdered,优先级最高排前面
  2. 如果都实现了PriorityOrdered或者,都没有实现PriorityOrdered接口,就比较order值
  3. order值优先从Ordered接口的getOrder方法获取
  4. 其次从注解Order的value值获取
  5. 或者从注解javax.annotation.Priority的value值获取
  6. 都没取到,就取默认值Integer.MAX_VALUE

比如监听器的排序

ClearCachesApplicationListener  Integer.MAX_VALUE
ParentContextCloserApplicationListener  Integer.MAX_VALUE - 10
FileEncodingApplicationListener    Integer.MAX_VALUE
AnsiOutputApplicationListener			Integer.MIN_VALUE + 10 + 1
DelegatingApplicationListener		0
LoggingApplicationListener			Integer.MAX_VALUE
EnvironmentPostProcessorApplicationListener  Integer.MIN_VALUE + 10
BackgroundPreinitializer Integer.MIN_VALUE + 20 + 1

最终排序为:

  1. DelegatingApplicationListener
  2. EnvironmentPostProcessorApplicationListener
  3. AnsiOutputApplicationListener
  4. ParentContextCloserApplicationListener
  5. BackgroundPreinitializer
  6. ClearCachesApplicationListener
  7. FileEncodingApplicationListener
  8. LoggingApplicationListener

除了监听器,多个地方用到了排序
在这里插入图片描述
这里只是查找了SpringBoot代码,Spring中也有。

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值