Spring 在classpath中扫描组件
2016-07-30 14:52
393 查看
Spring 在classpath中扫描组件
组件扫描(component scanning):Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件。特定组件包括:
-@Component:基本注解,标识了一个受Spring管理的组件
-@Repository:标识持久层组件
-@Service:标识服务层(业务层)组件
-@Controller:标识表现层组件
对于扫描到的组件,Spring有默认的命名策略:使用非限定类名,第一个字母小写,也可以在注解中通过value属性值标识组件的名称。
服务层:
@Service public class UserServiceImpl { private void save() { System.out.println("service...."); } }
持久层:
@Repository("userDao") public class UserDaoImpl implements UserDao { @Override public void save() { System.out.println("repository"); } }
控制层:
@Controller public class UserController { private void save() { System.out.println("controller..."); } }
基本注解:
@Component public class TestAnnotation { }
在classpath中扫描组件
当在组件类上使用特定的注解之后,还需要在Spring的配置文件中声明< context:component-scan>:
-base-package属性指定一个需要扫描的基类包,Spring容器将会扫描这个基类包里及其中子包中的所有类。
-当需要扫描多个包时,可以使用逗号分隔。
-如果仅希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类,
< !– 指定Spring IOC容器扫描的包 –>
< !– 可以通过 resource-pattern指定扫描的资源–>
< context:component-scan base-package=”com.metadata.annotation” resource-pattern=”service/*.class” />
-< context:include-filter>子节点表示要包含的目标类
-< context:exclude-filter>子节点表示要排除在外的目标类
-< context:component-scan>下可以拥有若干个< context:include-filter>和< context:exclude-filter>子节点
<!--context:exclude-filter 子节点指定排除哪些指定表达式的组件 --> <!--context:include-filter 子节点指定包含哪些表达式的组件,该子节点需要 use-default-filters 配合使用 --> <context:component-scan base-package="com.metadata.annotation" use-default-filters="false" > <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
< context:exclude-filter>和< context:include-filter>子节点支持多种类型的过滤出表达式:
<context:component-scan base-package="com.metadata.annotation" use-default-filters="true" > <context:exclude-filter type="assignable" expression="com.metadata.annotation.controller.UserController"/> </context:component-scan>
相关文章推荐
- 一个jar包里的网站
- 一个jar包里的网站之文件上传
- 一个jar包里的网站之返回对媒体类型
- Spring和ThreadLocal
- Spring Boot 开发微服务
- Spring AOP动态代理-切面
- Spring整合Quartz(JobDetailBean方式)
- Spring整合Quartz(JobDetailBean方式)
- 模拟Spring的简单实现
- Spring整合WebSocket应用示例(上)
- spring+html5实现安全传输随机数字密码键盘
- Spring中属性注入详解
- 监听器获取Spring配置文件的方法
- Spring Boot 定制URL匹配规则的方法
- Java利用Sping框架编写RPC远程过程调用服务的教程
- springmvc 发送ajax出现中文乱码的解决方法汇总
- Spring MVC中Ajax实现二级联动的简单实例
- SpringMVC框架下JQuery传递并解析Json格式的数据是如何实现的
- 详解Java的MyBatis框架和Spring框架的整合运用