基于注解配置bean
1.概述
組件掃描(component scanning):Spring能夠從classpath下自動(dòng)掃描具有特定注解的組件
注解類(lèi)型包含:
@Component:基本注解,標(biāo)識(shí)該組件受Spring管理
@Respository:持久層組件標(biāo)識(shí)
@Service:服務(wù)層組件標(biāo)識(shí)
@Controller:表現(xiàn)層組件標(biāo)識(shí)
生成的對(duì)象命名規(guī)則,默認(rèn)使用類(lèi)名且首字母小寫(xiě),可在注解中用value標(biāo)識(shí)名稱(chēng)
2.屬性context:component-scan
使用注解類(lèi)型注解類(lèi)
idea在編寫(xiě)xml時(shí),引入context時(shí),一定要在schemaLocation中添加
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd否則會(huì)報(bào):<font color="#ff0000">通配符的匹配很全面, 但無(wú)法找到元素 '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:掃描過(guò)濾,值為過(guò)濾條件
<context:component-scan base-package="com.spring.annotation" resource-pattern="repository/*.class"></context:component-scan>
3.context:component-scan子節(jié)點(diǎn)
context:exclude-filter:要包含的目標(biāo)類(lèi)
context:include-filter:要排除的目標(biāo)
type屬性值有5種類(lèi)型:
annotation:根據(jù)注入的類(lèi)型指定
assinable:根據(jù)具體的類(lèi)名和接口名
aspecj:采用AspejcJ表達(dá)式進(jìn)行過(guò)濾
regex:采用正則表達(dá)式根據(jù)類(lèi)名過(guò)濾
custom:實(shí)現(xiàn)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:設(shè)置use-default-filters="false",只會(huì)注入Repository,否則會(huì)加載所有的
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:排除該類(lèi)和該類(lèi)所有的實(shí)現(xiàn)類(lèi)
<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>