注解

来源:互联网 发布:java 微信菜单开发 编辑:程序博客网 时间:2024/06/07 22:38


                                                                                                                               

bean配置不仅可以通过xml文件配置,还可以通过注解实现bean配置,如果采用基于注解的配置文件,则bean定义信息通过在Bean实现类上标注注解实现。特定注解组件包括:
@Component:基本注解,标识了一个受Spring管理的Bean组件
@Service:标识服务层(业务层)Bean组件
@Repository:标识持久层Bean组件
@Controller:标识表现层Bean组件

一、如何通过注解配置bean
1、通过上述注解对此类进行标注

package com.gec.controller;import org.springframework.stereotype.Controller;@Controllerpublic class MyController {}


2、扫描
 a、配置文件引入context命名空间
  <!-- 扫描类包以应用注解定义的Bean -->
  <context:component-scan base-package="com.gec.controller" />

3、导入相应的库
 aspectjweaver.jar
 spring-aop-4.3.6.RELEASE.jar
 spring-aspects-4.3.6.RELEASE.jar


二、扫描类过滤条件 :减少粒度
<context:include-filter>:表示要包含的目标类
 annotation:扫描带有注解的类
 assignable:指明类进行扫描

 aspectj:按自定义的表达式进行扫描
<context:exclude-filter>:表示要排除的目标类

注意:在使用过滤来添加注解时一定要记得加上use-default-filters="false"属性才能生效

<context:component-scan base-package="com.gec.*"  use-default-filters="false"><!-- 扫描类过滤条件 --><!-- 所有添加了@Controller注解的类 --><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/><!-- 所有类名为 com.gec.service.MyService的类及其子类--><context:include-filter type="assignable" expression="com.gec.service.MyService"/><!-- 所有com.gec.dao包下以Dao结尾的类及其子类 --><context:include-filter type="aspectj" expression="com.gec.dao.*Dao+"/><context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/><context:include-filter type="assignable" expression="com.gec.service.BookService"/><context:include-filter type="assignable" expression="com.gec.controller.BookController"/></context:component-scan>


0 0
原创粉丝点击