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

转载于:https://www.cnblogs.com/lemonbar/p/3904542.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值