您的位置:首页 > 编程语言 > Java开发

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

2015-07-04 14:02 501 查看
上篇文章我们引入注解,在配置中用到了<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 Typedesc
annotation过滤器扫描使用指定注解所标注的那些类。通过expression属性指定要扫描的注解
assignable过滤器派生于expression属性所指定类型的那些类
aspectj过滤器扫描于expression属性所指定的Aspectj表达式所匹配的那些类
custom使用自定义的org.springframework.core.type.filter.TypeFilter实现类,该类由expression属性指定
regex过滤器扫描类的名称于expression属性所指定的正则表达式所匹配的那些类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息