我正在阅读SpringApplication.java的源代码。我以一种复杂的方式加载了ApplicationContextInitializer和ApplicationListener:
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<String>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}为什么不直接用new关键字创建这些工厂实例呢?
发布于 2018-02-02 08:29:16
Spring的默认作用域总是单例。Singleton在上下文或容器中是唯一的。例如,在您的示例中,似乎每个上下文都有一个实例:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<String>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);最后一行:
AnnotationAwareOrderComparator.sort(instances);正如我所设想的那样,orders实例用于加载:
创造的顺序对春天很重要。在消化了配置元数据之后,Spring创建了一个计划(它为每个bean分配了某些优先级),并且需要创建bean的顺序来满足依赖关系。
之所以是AnnotationAwareOrderComparator,是因为Spring中支持基于注释的排序,支持多种组件。例如(第44.2款):
如果您的配置需要按特定顺序应用,则可以使用@AutoConfigureAfter或@AutoConfigureBefore注解。
发布于 2018-02-02 08:34:33
我认为其背后的原因是松散耦合,可重用性,ApplicationContextInitializer是接口,在spring应用程序中有许多类,如AutoConfigurationReportLoggingInitializer、ConfigFileApplicationContextInitializer、ContextCustomizerAdapter等,还有许多实现ApplicationContextInitializer的类,所以如果使用新关键字,就会出现紧耦合,这违背了自己的弹簧原则(松耦合、依赖注入)。
https://stackoverflow.com/questions/48578471
复制相似问题