我正在学习Spring 3,我似乎没有掌握<context:annotation-config>和<context:component-scan>背后的功能。

从我读到的内容来看,它们似乎处理不同的注释(@Required, @Autowired等vs @Component, @Repository, @Service等),但从我读到的内容来看,它们注册了相同的bean后处理器类。

更让我困惑的是,在<context:component-scan>上有一个annotation-config属性。

有人能解释一下这些标签吗?什么是相似的,什么是不同的,是一个被另一个取代,它们互相完善,我需要其中一个吗,还是两个?


当前回答

<context:component-scan base-package="package name" />:

这用于告诉容器在我的包中有bean类,扫描这些bean类。为了在bean的顶部通过容器扫描bean类,我们必须像下面这样编写一个立体类型注释。

@组件,@服务,@存储库,@控制器

<上下文:annotation-config / >:

如果我们不想显式地用XML写bean标签,那么容器如何知道bean中是否有自动连接。这可以通过使用@Autowired注释实现。我们必须通过上下文:annotation-config通知容器,在我的bean中有自动连接。

其他回答

>激活bean中许多不同的注释,无论它们是用XML定义的还是通过组件扫描定义的。

>用于不使用XML定义bean

欲了解更多信息,请阅读:

3.9. 基于注释的容器配置 3.10. 类路径扫描和托管组件

<context:annotation-config>:扫描并激活spring config xml中已注册bean的注释。

<context:component-scan>: Bean注册+ <context:annotation-config>


@Autowired和@Required是目标属性级别,所以bean应该在使用这些注释之前在spring IOC中注册。要启用这些注释,要么必须注册各自的bean,要么包含<context:annotation-config />。例如,<context:annotation-config />仅适用于已注册的bean。

@Required启用RequiredAnnotationBeanPostProcessor处理工具 @Autowired启用AutowiredAnnotationBeanPostProcessor处理工具

注:注释本身没什么事,我们需要一个Processing Tool,它是底层的一个类,负责核心流程。


@Repository, @Service和@Controller是@Component,它们的目标是类级别。

<context:component-scan>它扫描包并找到并注册bean,它包括<context:annotation-config />所做的工作。

将XML迁移到注释

我发现了一个很好的总结,说明哪些注释被哪些声明拾取。通过研究它,你会发现<context:component-scan/>识别了<context:annotation-config/>识别的注释的超集,即:

@组件,@服务,@存储库,@控制器,@端点 @Configuration, @Bean, @Lazy, @Scope, @Order, @Primary, @Profile, @DependsOn, @Import, @ImportResource

正如您所看到的,<context:component-scan/>逻辑上扩展了<context:annotation-config/>,具有CLASSPATH组件扫描和Java @Configuration特性。

<context:annotation-config/> <!-- is used to activate the annotation for beans -->
<context:component-scan base-package="x.y.MyClass" /> <!-- is for the Spring IOC container to look for the beans in the base package. -->

要注意的另一个重要点是context:component-scan隐式调用context:annotation-config来激活bean上的注释。如果你不想让context:component-scan隐式地为你激活注释,你可以继续将context:component-scan的annotation-config元素设置为false。

总结:

<context:annotation-config/> <!-- activates the annotations --> 
<context:component-scan base-package="x.y.MyClass" /> <!-- activates the annotations + register the beans by looking inside the base-package -->

作为补充,您可以使用@ComponentScan以注释的方式使用<context:component-scan>。

在spring.io中也有描述

配置使用with的组件扫描指令 @ configuration类。提供与Spring XML并行的支持 元素。

需要注意的一点是,如果您正在使用SpringBoot, @Configuration和@ComponentScan可以通过使用@SpringBootApplication注释来暗示。