您的当前位置:首页正文

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

2024-12-01 来源:个人技术集锦

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));
}

排序逻辑:

比如监听器的排序

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

除了监听器,多个地方用到了排序

显示全文