@Order注解和Ordered接口如何發揮作用


1、@Order注解與Ordered接口實現相同的邏輯

@Order實現的是同一類組件或者bean的執行順序,不是實例化順序,也不是組件在IOC容器的注入順序。

邏輯解析:

  • 存在多個同類(接口)組件,組件之間可能需要按某個順序執行,使用@Order注解標注執行順序;
  • 組件會在各業務配置階段被無序的加入到容器中,被容器包裹,比如ArrayList中添加需要執行的組件,暫時稱這個容器為listA;
  • 此時,業務類B持有容器ListA,它需要按順序注冊或者執行容器里的組件;
  • 常規情況下,業務類B會調用AnnotationAwareOrderComparator.sort(listA)對容器里的組件按@Order注解排序,如果沒有Order注解則排最后;
  • 最后,按照業務邏輯循環listA,取出每一個組件執行業務邏輯。

2、AnnotationAwareOrderComparator

AnnotationAwareOrderComparator是OrderComparator的子類,它支持Spring的org.springframework.core.Ordered接口以及@Order和@Priority注解,其中Ordered接口實例提供的order值將覆蓋靜態定義的注解值(如果有)。

AnnotationAwareOrderComparator就是比較器的Order注解和接口實現。

AnnotationAwareOrderComparator -> OrderComparator -> Comparator

以CommandLineRunner接口為例,我們可以在實現CommandLineRunner接口的類上標注@Order注解以便為多個CommandLineRunner執行排序。

在Springboot啟動時,對CommandLineRunner接口進行排序並執行

	private void callRunners(ApplicationContext context, ApplicationArguments args) {
		List<Object> runners = new ArrayList<>();
		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
		AnnotationAwareOrderComparator.sort(runners);
		for (Object runner : new LinkedHashSet<>(runners)) {
			if (runner instanceof ApplicationRunner) {
				callRunner((ApplicationRunner) runner, args);
			}
			if (runner instanceof CommandLineRunner) {
				callRunner((CommandLineRunner) runner, args);
			}
		}
	}

可以看到調用接口前通過AnnotationAwareOrderComparator.sort(runners)靜態方法對所有ApplicationRunner和CommandLineRunner進行排序。

在調用鏈從AnnotationAwareOrderComparator的findOrderFromAnnotation到OrderUtils的findOrder靜態方法獲取到類上Order注解。

AnnotationAwareOrderComparator

	@Nullable
	private Integer findOrderFromAnnotation(Object obj) {
		AnnotatedElement element = (obj instanceof AnnotatedElement ? (AnnotatedElement) obj : obj.getClass());
		MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY);
		Integer order = OrderUtils.getOrderFromAnnotations(element, annotations);
		if (order == null && obj instanceof DecoratingProxy) {
			return findOrderFromAnnotation(((DecoratingProxy) obj).getDecoratedClass());
		}
		return order;
	}

OrderUtils

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

3、結論

在Springboot中,組件容器的持有者需要在邏輯執行前調用AnnotationAwareOrderComparator.sort,給容器內的組件排序,然后標注過@Order注解、@Priority注解或者實現Ordered接口的組件才能才能按既定的排序執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM