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

王朝学院·作者佚名  2016-05-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

[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中的。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航