Spring自动组件扫描
通常情况下,在XML bean配置文件声明所有的Bean类或组件,这样Spring容器可以检测并注册Bean类或组件。 其实,Spring是能够自动扫描,检测和预定义的项目包并实例化bean,不再有繁琐的Bean类声明在XML文件中。
1. 开启Spring自动扫描功能
在bean配置文件中配置“context:component”表亲啊,这意味着,在 Spring 中启用自动扫描功能。base-package 是指明存储组件,Spring将扫描该文件夹,并找出Bean(注解为@Component)并注册到 Spring 容器:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.myprj.customer" />
</beans>
2. 使用@Component注解
使用@Component注释来表示该类是一个自动扫描组件。
3. 自定义自动扫描组件名称
你可以这样创建自定义名称:
@Service("AAA")
public class CustomerService
...
现在,可以用’AAA’这个名称进行检索。
CustomerService cust = (CustomerService)context.getBean("AAA");
4. 自动组件扫描注释类型
在Spring2.5中,有4种类型的组件自动扫描注释类型
- @Component – 指示自动扫描组件。
- @Repository – 表示在持久层DAO组件。
- @Service – 表示在业务层服务组件。
- @Controller – 表示在表示层控制器组件。
5. Spring过滤器组件自动扫描
5.1 过滤组件 - 包含
使用Spring “过滤” 扫描并注册匹配定义“regex”,即使该类组件的名称未标注 @Component 也能被注册到Spring容器中:
<context:component-scan base-package="com.myprj" >
<context:include-filter type="regex"
expression="com.myprj.customer.dao.*DAO.*" />
<context:include-filter type="regex"
expression="com.myprj.customer.services.*Service.*" />
</context:component-scan>
在这个XML过滤中,所有文件的名称中包含 DAO 或 Service(DAO., Services.) 单词将被检测并在 Spring 容器中注册。
5.2 过滤组件 - 不包含
另外,您还可以排除指定组件,以避免 Spring 检测和 Spring 容器注册。
如不包括在这些文件中标注有 @Service :
<context:component-scan base-package="com.myprj.customer" >
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>