[Spring Framework]学习笔记--@Component等stereotype的基础

时间:2023-03-10 06:34:20
[Spring Framework]学习笔记--@Component等stereotype的基础

在继续讲解Spring MVC之前,需要说一下常用的几个用来标记stereotype的annotation。

@Component,@Controller,@Repository,@Service。

这四个都在org.springframework.stereotype包下面,后面3个都属于@Component。

可以理解为@Component是@Controller,@Repository,@Service的基类。

@Component是用来标记任何被Spring管理的组件。

@Controller用来标记presentation层(比如web controller)。

@Repository用来标记persistence层(比如DAO)。

@Service用来标记service层。

如果我们为自己class增加了这些annotation后,如果让Spring自动找到这些class,并实现注册呢?

需要在Spring的xml中用到<context:component-scan>元素, base-package是要扫描的包名。

<beans
...
xmlns:context="http://www.springframework.org/schema/context"
...>
<context:component-scan base-package="xxx.xxx"/>
</beans>

<context:component-scan>的使用,是默认激活<context:annotation-config>功能的。而<context:annotation-config>又是干啥的呢?

主要是为@Autowired服务的(换句话就是说,使Spring可以处理像@Autowired和@Configuration这样的annotations),试想一下,如果没有<context:annotation-config>, 我们需要在Spring的XML文件中去注册每一个bean,

导致整个XML文件非常大,而且难以维护。现在用一行,就可以来实现注册,简单方便。

注意1:如果有了<context:component-scan>, 我们是不需要显式的来定义<context:annotation-config>的。

注意2:<context:annotation-config>只搜索在同一个application context下的被annotation标记的beans。

举个例子,就是如果<context:annotation-config>加在WebApplicationContext下,它只检查在controller中被标记为Autowired的beans,不会检查service中的。