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

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

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

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


当前回答

<上下文:annotation-config >:

这告诉Spring,我将使用Annotated bean作为Spring bean,这些将通过@Autowired annotation进行连接,而不是在Spring配置xml文件中声明。

<上下文:component-scan基础包= " com.test……“>:

这告诉Spring容器从哪里开始搜索那些带注释的bean。在这里,spring将搜索基本包的所有子包。

其他回答

我发现了一个很好的总结,说明哪些注释被哪些声明拾取。通过研究它,你会发现<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 -->

<context:annotation-config>标记告诉Spring扫描代码库,以自动解决包含@Autowired注释的类的依赖关系需求。

Spring 2.5还增加了对JSR-250注释的支持,比如@Resource、@PostConstruct和@PreDestroy。使用这些注释还要求在Spring容器中注册某些beanpostprocessor。与往常一样,这些可以注册为单独的bean定义,但也可以通过在spring配置中包含<context:annotation-config>标记来隐式注册。

摘自Spring文档中的基于注释的配置


Spring提供了自动检测“定型”类的功能,并在ApplicationContext中注册相应的BeanDefinitions。

根据org.springframework.stereotype的javadoc:

原型是表示类型或方法在整个体系结构中的角色的注释(在概念级别,而不是实现级别)。 例如:@控制器@服务@存储库等。 它们是供工具和方面使用的(成为切入点的理想目标)。

要自动检测这样的“原型”类,需要<context:component-scan>标记。

<context:component-scan>标记还告诉Spring在指定的包(及其所有子包)下扫描可注入bean的代码。

<context:component-scan/>自定义标记除了主要负责扫描java包和从类路径注册bean定义外,还注册了与by所做的相同的bean定义集。

如果出于某种原因要避免这种默认bean定义的注册,方法是在component-scan中指定一个额外的“annotation-config”属性,如下所示:

<context:component-scan basePackages="" annotation-config="false"/>

参考: http://www.java-allandsundry.com/2012/12/contextcomponent-scan-contextannotation.html

<上下文:annotation-config >:

这告诉Spring,我将使用Annotated bean作为Spring bean,这些将通过@Autowired annotation进行连接,而不是在Spring配置xml文件中声明。

<上下文:component-scan基础包= " com.test……“>:

这告诉Spring容器从哪里开始搜索那些带注释的bean。在这里,spring将搜索基本包的所有子包。