基于注解配置bean
1.概述
组件扫描(component scanning):Spring能够从classpath下自动扫描具有特定注解的组件
注解类型包含:
@Component:基本注解,标识该组件受Spring管理
@Respository:持久层组件标识
@Service:服务层组件标识
@Controller:表现层组件标识
生成的对象命名规则,默认使用类名且首字母小写,可在注解中用value标识名称
2.属性context:component-scan
使用注解类型注解类
idea在编写xml时,引入context时,一定要在schemaLocation中添加
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
否则会报:<font color="#ff0000">通配符的匹配很全面, 但无法找到元素 'context:component-scan' 的声明</font>
base-package:指定扫描包名
Java代码:
package com.spring.annotation;
import org.springframework.stereotype.Component;
@Component(value="JJY")
public class AnnotationComponent {
private String name="JJY";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "AnnotationComponent{" +
"name='" + name + '\'' +
'}';
}
}
xml代码:
<context:component-scan base-package="com.spring.annotation"></context:component-scan>
resource-pattern:扫描过滤,值为过滤条件
<context:component-scan base-package="com.spring.annotation" resource-pattern="repository/*.class"></context:component-scan>
3.context:component-scan子节点
context:exclude-filter:要包含的目标类
context:include-filter:要排除的目标
type属性值有5种类型:
annotation:根据注入的类型指定
assinable:根据具体的类名和接口名
aspecj:采用AspejcJ表达式进行过滤
regex:采用正则表达式根据类名过滤
custom:实现org.springframework.type.TypeFilter接口,自定义筛选
annotation:
context:exclude-filter:排除Repository的注解
xml代码:
<context:component-scan base-package="com.spring.annotation">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"></context:exclude-filter>
</context:component-scan>
context:include-filter:设置use-default-filters="false",只会注入Repository,否则会加载所有的
xml代码:
<context:component-scan base-package="com.spring.annotation" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"></context:include-filter>
</context:component-scan>
assinable:
context:exclude-filter:排除该类和该类所有的实现类
<context:exclude-filter type="assignable" expression="com.spring.annotation.repository.UserRepository"></context:exclude-filter>
context:include-filter:只包含UserRepository
<context:include-filter type="assignable" expression="com.spring.annotation.repository.UserRepository"></context:include-filter>