【Spring学习】spring注解自动注入bean

Spring mvc注解用到的配置:

<!-- 启用spring mvc 注解 -->
<context:annotation-config />  
 <context:component-scan base-package="cn.itkt"></context:component-scan>  

这样的话,在com包及其所有子包下的所有类如果含有@Component、@Controller、@Service、@Repository等注解的 话都会自动纳入到Spring容器中,但是每个类都一个个加上注解,有时难免觉得繁琐,其实Spring也为我们提供了自动为类加上注解的功能。配置如 下:

<!-- 启用spring mvc 注解 -->
    <context:annotation-config />
    <!-- 设置使用注解的类所在的包 -->
    <context:component-scan base-package="com.lmb.**.rest,com.lmb..server.http,com.lmb.**.mvc">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>

com.lmb..rest,com.lmb.hollyuniproxy.server.http,com.lmb..mvc包下的类都为使用注解的类。

要特别注意其中的context:include-filter标签和context:exclude-filter标签:
context:include-filter
此标签的含义是:在其扫描到的所有包下的类,全部自动加上注解并纳入Spring容器中。
比如下面这个类:

public class InterfaceVisitService implements IInterfaceVisitService  {  
//……
} 

那么该标签等于为InterfaceVisitService 类加上@Component注解,且bean的id为interfaceVisitService。

@Component(“interfaceVisitService”)
public class InterfaceVisitService implements IInterfaceVisitService  {  
//……
} 

context:exclude-filter
此标签的含义是:排除扫描到的所有类,不纳入Spring容器中。
但需要注意的是,采用自动注入,类名不能相同(即便包名不同),因为自动注入时,id与类名相同,所以如果两个类名一样的话,会因为Bean的id相同而报错。如果类名一定要相同的话,只能是其中一个类,手动加上注解并将名称改为其他。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值