码迷,mamicode.com
首页 > 编程语言 > 详细

spring组件<context:component-scan>详解

时间:2015-07-04 15:36:43      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:spring   component-scan   spring注解   annotation   

上篇文章我们引入注解,在配置中用到了<context:annotation-config/>有助于完全消除Spring配置中的<property>和<constructor-arg>元素,我们仍需要使用<bean>元素显示定义Bean。

但是Spring还有另一种技巧<context:component-scan>元素除了完成与<context:annotation-config>一样的工作,还允许Spring自动检测Bean和定义的Bean。这意味着不使用<bean>元素,Spring应用大多数(或者所有)Bean都能够实现定义和装配。

<context:component-scan 
		base-package="cn.com.ztz.spring.*">
	</context:component-scan>

<context:component-scan>元素会扫描指定的包及其所有的子包,并查找出能够自动注册为Spring Bean的类。base-package属性标识了<context:component-scan>元素所扫描的包。

那么<context:component-scan>又是如何知道哪些类需要注册为Spring Bean呢?带着疑问,我们继续往下看:

1、为自动检测标注Bean

默认情况下<context:component-scan>查找使用构造型注解所标注的类,这些特殊的注解如下:

  • @Component 通用的构造型注解,标识该类为Spring组件()
  • @Controller 标识将该类定义为Spring MVC controller(控制层)
  • @Repository 标识将该类定义为数据仓库(持久层)
  • @Service 标识将该类定义为服务(服务层,也就是业务层)
直接看下例子:
@Component
public class Roles {
	private int id=1;
	private String roleName="管理员";
	@Autowired  
    private Users users; 
	//重写toString方法,方便测试
	@Override
	public String toString() {
		return "Roles [id=" + id + ", roleName=" + roleName + ", users="
				+ users + "]";
	}
}
@Component
public class Users {
	private int id=2;
	private String name="张三";
	@Override
	public String toString() {
		return "Users [id=" + id + ", name=" + name + "]";
	}

	
}
<context:component-scan 
		base-package="cn.com.ztz.spring.*">
</context:component-scan>

运行测试方法:
@RunWith(SpringJUnit4ClassRunner.class)    
@ContextConfiguration(locations={"classpath:applicationContext.xml"})    
public class SpringTest {  
    @Autowired  
    private Roles roles;  
    @Test  
    public void testSpring(){  
       System.out.println(roles);  
    }  
}  
输出结果:
Roles [id=1, roleName=管理员, users=Users [id=2, name=张三]]

我们看到,Spring xml配置中完全消除了<bean>。


2、过滤组建扫描

<context:component-scan>提供两个子标签:<context:include-filter>和<context:exclude-filter>各代表引入和排除的过滤。
使用5种过滤类型的任意一种来定义组件扫描方式
Filter Type desc
annotation 过滤器扫描使用指定注解所标注的那些类。通过expression属性指定要扫描的注解
assignable 过滤器派生于expression属性所指定类型的那些类
aspectj 过滤器扫描于expression属性所指定的Aspectj表达式所匹配的那些类
custom 使用自定义的org.springframework.core.type.filter.TypeFilter实现类,该类由expression属性指定
regex 过滤器扫描类的名称于expression属性所指定的正则表达式所匹配的那些类



版权声明:本文为博主原创文章,未经博主允许不得转载。

spring组件<context:component-scan>详解

标签:spring   component-scan   spring注解   annotation   

原文地址:http://blog.csdn.net/luckey_zh/article/details/46755033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!