創(chuàng)建應(yīng)用對(duì)象之間協(xié)作關(guān)系的行為通常被稱(chēng)作裝配(Wiring),這也是依賴(lài)注入的本質(zhì)。
聲明Bean
創(chuàng)建Spring配置
Spring容器提供了兩種配置Bean的方式,其一是使用XML文件作為配置文件,其二是基于Java注解的配置方式。
以下是一個(gè)典型的Spring XML配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 此處聲明各個(gè)Bean -->
</beans>
在<beans>標(biāo)簽內(nèi)可以放置相關(guān)的Spring配置信息,另外,Spring的核心框架自帶了10個(gè)命名空間的配置:
| 命名空間 | 用途 |
|---|---|
| aop | 為聲明切面以及將@AspectJ注解的類(lèi)代理為Spring切面提供了配置元素 |
| beans | beans支持聲明Bean和裝配Bean,是Spring最核心也是最原始的命名空間 |
| context | 為配置Spring應(yīng)用上下文提供了配置元素,包括自動(dòng)檢測(cè)和自動(dòng)裝配Bean、注入非Spring直接管理的對(duì)象 |
| jee | 提供了與Java EE API 的集成,例如JNDI和EJB |
| jms | 為聲明消息驅(qū)動(dòng)的POJO提供了配置元素 |
| lang | 支持配置由Groovy、JRuby或BeanShell等腳本實(shí)現(xiàn)的Bean |
| mvc | 啟用Spring MVC的能力,例如面向注解的控制器、視圖控制器和攔截器 |
| oxm | 支持Spring 的對(duì)象到XML映射配置 |
| tx | 提供聲明式事務(wù)配置 |
| util | 提供各種各樣的工具類(lèi)元素,包括把集合配置為Bean、支持屬性占位符元素 |
聲明一個(gè)簡(jiǎn)單的Bean
package com.springinaction.springidol;
public class Juggler implements Performer {
private int beanBags = 3;
public Juggler() {
}
public Juggler(int beanBags) {
this.beanBags = beanBags;
}
@Override
public void perform() throws PerformanceException {
System.out.println("JUGGLING " + beanBags + " BEANBAGS");
}
}
<bean id="duke" class="com.springinaction.springidol.Juggler"></bean>
<bean>元素是Spring中最基本的配置單元,通過(guò)該元素Spring將創(chuàng)建一個(gè)對(duì)象。當(dāng)Spring容器加載該Bean時(shí),Spring將使用默認(rèn)的構(gòu)造器來(lái)實(shí)例化該Bean,實(shí)際上,duke會(huì)使用如下代碼來(lái)創(chuàng)建:
new com.springinaction.springidol.Juggler();
通過(guò)構(gòu)造器注入
讓bean使用另外一個(gè)構(gòu)造方法:
<bean id="duke" class="com.springinaction.springidol.Juggler">
<constructor-arg value="15"></constructor-arg>
</bean>
在構(gòu)造Bean的時(shí)候,可以使用<constructor-arg>標(biāo)簽來(lái)告訴Spring額外的信息,這樣Spring就不再會(huì)使用默認(rèn)的構(gòu)造器來(lái)實(shí)例化該Bean。
測(cè)試代碼:
package com.springinaction.springidol;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void testDuke() throws PerformanceException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-idol.xml");
Performer performer = (Performer) context.getBean("duke");
performer.perform();
}
}
通過(guò)運(yùn)行結(jié)果JUGGLING 15 BEANBAGS可以15被注入到了構(gòu)造器中。
通過(guò)構(gòu)造器注入對(duì)象引用
現(xiàn)在需要一個(gè)新的類(lèi)PoeticJuggler,該類(lèi)需要Poem類(lèi)作為其參數(shù)并通過(guò)構(gòu)造器注入。
package com.springinaction.springidol;
public class PoeticJuggler extends Juggler {
private Poem poem;
// 注入Poem
public PoeticJuggler(Poem poem) {
super();
this.poem = poem;
}
// 注入豆袋子數(shù)量和Poem
public PoeticJuggler(int beanBags, Poem poem) {
super(beanBags);
this.poem = poem;
}
@Override
public void perform() throws PerformanceException {
super.perform();
System.out.println("While reciting...");
poem.recite();
}
}
在配置文件中就需要聲明一個(gè) Poem的類(lèi),并將其注入到PoeticJuggler中:
<bean id="sonnet29" class="com.springinaction.springidol.Sonnet29"></bean>
<bean id="poeticDuke" class="com.springinaction.springidol.PoeticJuggler">
<constructor-arg value="15" />
<constructor-arg ref="sonnet29" />
</bean>
這里使用ref屬性來(lái)將Id為sonnet29的Bean引用傳遞給構(gòu)造器,當(dāng)Spring遇到sonnet29和poeticDuke的bean聲明時(shí),所執(zhí)行的邏輯腳本將是:
Poem sonnet29 = new Sonnet29();
Performer poeticDuke = new PoeticJuggler(15, sonnet29 );
通過(guò)工廠方法創(chuàng)建Bean
在沒(méi)有公開(kāi)的構(gòu)造方法時(shí),可以通過(guò)工廠方法來(lái)創(chuàng)建Bean,及<bean>元素的factory-method屬性來(lái)裝配工廠創(chuàng)建的Bean。
比如Stage是一個(gè)沒(méi)有公開(kāi)構(gòu)造方法的類(lèi),但是可以通過(guò)getInstance獲取其實(shí)例,那么可以通過(guò)下面的配置方式:
<bean id="theStage" class="com.springinaction.springidol.Stage"
factory-method="getInstance" />
Bean的作用域
| 作用域 | 定義 |
|---|---|
| singleton(默認(rèn)) | 在每一個(gè)Spring容器中,一個(gè)Bean定義只有一個(gè)對(duì)象實(shí)例 |
| prototype | 允許Bean的定義可以被實(shí)例化任意次(每次調(diào)用都創(chuàng)建一個(gè)實(shí)例) |
| request | 在一次HTTP請(qǐng)求中,每個(gè)Bean定義對(duì)應(yīng)一個(gè)實(shí)例。該作用域僅在基于Web的Spring上下文(例如SpringMVC)中才有效 |
| session | 在一個(gè)HTTP Sesion中,每個(gè)Bean定義對(duì)應(yīng)一個(gè)實(shí)例。該作用域僅在基于Web的Spring上下文(例如SpringMVC)中才有效 |
| global-session | 在一個(gè)全局HTTP Sesion中,每個(gè)Bean定義對(duì)應(yīng)一個(gè)實(shí)例。該作用域僅在Portlet上下文中才有效 |
配置方法,設(shè)置<bean>標(biāo)簽的scope屬性:
<bean id="sonnet29" class="com.springinaction.springidol.Sonnet29" scope="prototype"/>
Spring的單例只能保證在每個(gè)應(yīng)用上下文中只有一個(gè)Bean的實(shí)例,你也可以通過(guò)定義多個(gè)<bean>的方式來(lái)實(shí)例化同一個(gè)Bean。
初始化和銷(xiāo)毀Bean
可以為Bean定義初始化和銷(xiāo)毀操作,只需使用init-method和destroy-method參數(shù)來(lái)配置<bean>標(biāo)簽即可。
比如,舞臺(tái)(Auditorium)需要在表演開(kāi)始前開(kāi)燈(turnOnLights),在結(jié)束時(shí)關(guān)燈(turnOffLights),那么就可以做下面的聲明:
<bean id="auditorium" class="com.springinaction.springidol.Auditorium"
init-method="turnOnLights" destroy-method="turnOffLights" />
默認(rèn)的init-method和destroy-method
可以使用<beans>的default-init-method和default-destroy-method為上下文中所有的Bean設(shè)置共同的初始化和銷(xiāo)毀方法。
注入Bean屬性
Spring可以借助屬性的set方法來(lái)配置屬性的值,以實(shí)現(xiàn)setter方式的注入。
下面是一個(gè)音樂(lè)家(Instrumentalist)類(lèi),它演奏時(shí)需要歌曲(song)和樂(lè)器(instrument)兩個(gè)屬性。
package com.springinaction.springidol;
public class Instrumentalist implements Performer {
private String song;
private Instrument instrument;
public Instrumentalist() {
}
public void perform() throws PerformanceException {
System.out.print("Playing " + song + " : ");
instrument.play();
}
public void setSong(String song) { // 注入歌曲
this.song = song;
}
public String getSong() {
return song;
}
public String screamSong() {
return song;
}
public void setInstrument(Instrument instrument) { // 注入樂(lè)器
this.instrument = instrument;
}
}
配置文件中需要為Instrumentalist 注入這兩個(gè)屬性的值。
注入簡(jiǎn)單值
使用<property>標(biāo)簽可以通過(guò)調(diào)用屬性的setter方法為Bean注入屬性,而類(lèi)似的<constructor-arg>是通過(guò)構(gòu)造函數(shù)注入的。
<bean id="kenny" class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="Happy" />
</bean>
<property>元素會(huì)指示Spring調(diào)用setSong()方法將song屬性的值設(shè)置為"Happy"。
注意value的屬性值可以指定數(shù)值型(int、float、Double等)以及boolean等,Spring在調(diào)用set方法前會(huì)自動(dòng)根據(jù)類(lèi)型進(jìn)行轉(zhuǎn)換。
引用其他Bean
在演奏家kenny中需要一個(gè)樂(lè)器,那么我們就可以為其引用一個(gè)實(shí)現(xiàn)了Instrument接口的樂(lè)器。
<bean id="saxphone" class="com.springinaction.springidol.Saxophone" />
<bean id="kenny" class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="Happy" />
<property name="instrument" ref="saxphone"></property>
</bean>
通過(guò)Performer接口引用一個(gè)參賽者,就可以產(chǎn)生任意類(lèi)型的參賽者進(jìn)行表演,面向接口編程和依賴(lài)注入實(shí)現(xiàn)了松耦合。
注入內(nèi)部Bean
前文中,演奏家使用的instrument是其他Bean都可以進(jìn)行共用的,若要獨(dú)用一個(gè)類(lèi),那么可以聲明一個(gè)類(lèi)為內(nèi)部Bean:
<bean id="kenny" class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="Happy" />
<property name="instrument">
<bean class="com.springinaction.springidol.Saxophone" />
</property>
</bean>
如上面的代碼,通過(guò)直接聲明一個(gè)<bean>元素作為<property>元素的子節(jié)點(diǎn)。內(nèi)部Bean不限于setter注入,也可以通過(guò)構(gòu)造方法注入。
內(nèi)部Bean沒(méi)有Id屬性,它們不能被復(fù)用,內(nèi)部Bean僅適用于一次注入,而不能被其他Bean引用。
裝配集合
| 集合元素 | 用途 |
|---|---|
| <list> | 裝配list類(lèi)型的數(shù)據(jù),允許重復(fù) |
| <set> | 裝配set類(lèi)型的數(shù)據(jù),不允許重復(fù) |
| <map> | 裝配map類(lèi)型的數(shù)據(jù),key和value可以是任意類(lèi)型 |
| <props> | 裝配properties類(lèi)型的數(shù)據(jù),key和value必須是String類(lèi)型 |
下面一個(gè)演奏家可以演奏多種樂(lè)器:
package com.springinaction.springidol;
import java.util.Collection;
public class OneManBand implements Performer {
public OneManBand() {
}
public void perform() throws PerformanceException {
// 遍歷演奏各個(gè)樂(lè)器
for (Instrument instrument : instruments) {
instrument.play();
}
}
private Collection<Instrument> instruments;
public void setInstruments(Collection<Instrument> instruments) {// 注入instruments集合
this.instruments = instruments;
}
}
裝配List、Set和Array
可以使用下面的方式裝配List,也可以使用<set>來(lái)裝配:
<bean id="hank" class="com.springinaction.springidol.OneManBand">
<property name="instruments">
<list>
<ref bean="guitar"/>
<ref bean="cymbal"/>
<ref bean="harmonica"/>
</list>
</property>
</bean>
裝配Map
當(dāng)OneManBand表演時(shí),perform()方法可以把樂(lè)器(instrument)的音符打印出來(lái),我們還想知道每個(gè)音符是由哪個(gè)樂(lè)器產(chǎn)生的,因此需要做以下改變:
package com.springinaction.springidol;
import java.util.Map;
public class OneManBandMap implements Performer {
public OneManBandMap() {
}
public void perform() throws PerformanceException {
for (String key : instruments.keySet()) {
System.out.print(key + " : ");
Instrument instrument = instruments.get(key);
instrument.play();
}
}
private Map<String, Instrument> instruments;
public void setInstruments(Map<String, Instrument> instruments) {// 以map類(lèi)型注入instruments
this.instruments = instruments;
}
}
Spring配置map注入:
<bean id="hankk" class="com.springinaction.springidol.OneManBandMap">
<property name="instruments">
<map>
<entry key="GUITAR" value-ref="guitar" />
<entry key="CYMBAL" value-ref="cymbal" />
<entry key="HARMONICA" value-ref="harmonica" />
</map>
</property>
</bean>
<map>中的<entry>元素由一個(gè)鍵和一個(gè)值組成,鍵和值可以是簡(jiǎn)單類(lèi)型,也可以是其他Bean的引用:
| 屬性 | 用途 |
|---|---|
| key | 指定map中entry的鍵為String |
| key-ref | 指定map中entry的鍵為Spring山下文中其他Bean的引用 |
| value | 指定map中entry的值為String |
| value-ref | 指定map中entry的值為Spring山下文中其他Bean的引用 |
裝配Properties集合
若OneManBandMap中的Instrument屬性所配置的Map的每一個(gè)entry的鍵和值都是String類(lèi)型,可以使用java.util.Properties來(lái)代替Map:
<bean id="hank" class="com.springinaction.springidol.OneManBand">
<property name="instruments">
<props>
<prop key="GUITAR">Strum Strum Strum</prop>
<prop key="CYMBAL">Crush Crush Crush</prop>
<prop key="HARMONICA">Hum Hum Hum</prop>
</props>
</property>
</bean>
- <property>元素用于把值或者Bean引用注入到Bean的屬性中;
- <props>用于定義一個(gè)
java.util.Properties類(lèi)型的集合值; - <prop>用于定義<props>集合的一個(gè)成員
裝配空值
<property name="someNonNullProperty"><null/></property>
使用表達(dá)式裝配
如果為屬性裝配的值只有在運(yùn)行期間才能獲取,那該如何實(shí)現(xiàn)?
Spring表達(dá)式語(yǔ)言( Spring Expression Language , SpEL),可以通過(guò)運(yùn)行期執(zhí)行的表達(dá)式將值裝配到Bean的屬性或者構(gòu)造器參數(shù)中,其特性有:
- 使用Bean的id來(lái)引用Bean;
- 調(diào)用方法和訪問(wèn)對(duì)象的屬性;
- 對(duì)值進(jìn)行算術(shù)、關(guān)系和邏輯運(yùn)算;
- 正則表達(dá)式匹配;
- 集合操作。
SpEL基本用法
字面值
比如<property name="count" value="#{5}"/>,#{ }標(biāo)記會(huì)提示Spring這是個(gè)SpEL表達(dá)式。
可以與非SpEL表達(dá)式混用:<property name="message" value="The value is #{5}"/>。
另外,浮點(diǎn)型、科學(xué)計(jì)數(shù)法、布爾型(true和false)也可以直接使用。
字符串使用時(shí),需要用單引號(hào)或者雙引號(hào)括起。
引用Bean、Properties和方法(避免空指針)
新聲明一個(gè)id為carl的模仿者,Kenny唱什么他就唱什么:
<bean id="carl" class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="#{kenny.song}" />
</bean>
注入到Carl的song屬性的表達(dá)式是由兩部分組成的,第一部分(kenny)指向了kenny的Bean,第二部分(song)指向了kenny Bean的song屬性,其實(shí)等價(jià)于下面的代碼:
Instrumentalist carl = new Instrumentalist();
carl.setSong(kenny.getSong());
還可以調(diào)用其他Bean的方法:
<property name="song" value="#{songSelector.selectSong()}"/>
<property name="song" value="#{songSelector.selectSong().toUpperCase()}"/>
如果selectSong()返回一個(gè)null,那么SpEL會(huì)拋出空指針異常,可以采用下面的方法避免:
<property name="song" value="#{songSelector.selectSong()?.toUpperCase()}"/>
使用?.來(lái)代替.來(lái)訪問(wèn)toUpperCase()方法,訪問(wèn)之前會(huì)確保左邊項(xiàng)不為null,若為null就不會(huì)再繼續(xù)調(diào)用。
操作類(lèi)
可以使用T()運(yùn)算符調(diào)用類(lèi)作用域的方法和常量。比如:
<property name="multiplier" value="#{T(java.lang.Math).PI}"/>
<property name="randomNumber" value="#{T(java.lang.Math).random()}"/>
在SpEL值上進(jìn)行操作
| 運(yùn)算符類(lèi)型 | 運(yùn)算符 | 例子 |
|---|---|---|
| 算術(shù)運(yùn)算 | +, -, *, /, %, ^ | #{T(java.lang.Math).PI * circle.radius ^ 2} |
| 關(guān)系運(yùn)算 | <, >, ==, <=, >=, lt,gt, eq, le, ge | #{counter.total == 100} |
| 邏輯運(yùn)算 | and, or, not(或!) | #{!product.available} |
| 條件運(yùn)算 | ?: (ternary), ?: (Elvis) | #{m>=n?m:n} |
| 正則表達(dá)式 | matches | #{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.com'} |
如果覺(jué)得有用,歡迎關(guān)注我的微信,有問(wèn)題可以直接交流:
