Spring自动组件扫描

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值