Spring自动扫描+注解注入

一、基本使用
可通过在配置文件content-xml中设置如下,即可使用spring组件注解,可以实现bean的自动载入。
<context:annotation-config />
<!-- 配置容器资源扫描的包 -->
<context:component-scan base-package="com.csair.baggage"></context:component-scan>
<context:annotation-config />   声明可以通过注解的方式,实现bean的初始化。
base-package 表明这个包以及它的子包都是在扫描的范围。只要有出现@Component,@Service,@Controller,@Repository都是会自动生成Bean的,如果不指定id的话,
一般都是以类名作为bean的名字。
@Service,@Controller,@Repository标注的是不同功能的bean,是@Component的细化。是为了更好的配置我们的bean,方便我们的使用。
@Repository对应了持久化层
@Service对应了服务层
@Service对应了表现层
二、其他标签
<context:component-scan>提供两个子标签:<context:include-filter><context:exclude-filter>各代表引入和排除的过滤。
代码如下:
 <context:component-scan base-package="com.csair"> 
   <context:exclude-filter type="annotation" 
    expression="org.springframework.stereotype.Controller"/> 
</context:component-scan>  
表示扫描com.csair包,含有Controller注解的就注册。用exclude-filter标签的就表示除了这个,其他的注解都会扫描。

posted on 2017-10-24 15:56  取个名字真的很难  阅读(5770)  评论(0编辑  收藏  举报

导航