标签: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呢?带着疑问,我们继续往下看:
1、为自动检测标注Bean
默认情况下<context:component-scan>查找使用构造型注解所标注的类,这些特殊的注解如下:
@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);
}
} 输出结果:| 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