?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
本章的大部分內(nèi)容的關(guān)注點(diǎn)都在描述Spring對(duì)動(dòng)態(tài)語言的支持的細(xì)節(jié)上。在深入到這些細(xì)節(jié)之前,首先讓我們看一個(gè)使用動(dòng)態(tài)語言定義的bean的快速上手的例子。第一個(gè)bean使用的動(dòng)態(tài)語言是Groovy(這個(gè)例子來自Spring的測試套件,如果你打算看看對(duì)其他語言的支持的相同的例子,請閱讀相應(yīng)的源碼)。
下面是Groovy bean要實(shí)現(xiàn)的Messenger
接口。注意該接口是使用純Java定義的。依賴的對(duì)象是通過Messenger
接口的引用注入的,并不知道其實(shí)現(xiàn)是Groovy腳本。
package org.springframework.scripting; public interface Messenger { String getMessage(); }
下面是依賴于Messenger
接口的類的定義。
package org.springframework.scripting; public class DefaultBookingService implements BookingService { private Messenger messenger; public void setMessenger(Messenger messenger) { this.messenger = messenger; } public void processBooking() { // use the injected Messenger object... } }
下面是使用Groovy實(shí)現(xiàn)的Messenger
接口。
// from the file 'Messenger.groovy' package org.springframework.scripting.groovy; // import the Messenger interface (written in Java) that is to be implemented import org.springframework.scripting.Messenger // define the implementation in Groovy class GroovyMessenger implements Messenger { String message }
最后,這里的bean定義將Groovy定義的Messenger
實(shí)現(xiàn)注入到DefaultBookingService
類的實(shí)例中。
要使用用戶定制的動(dòng)態(tài)語言標(biāo)簽來定義 dynamic-language-backed bean,需要在Spring XML配置文件的頭部添加相應(yīng)的XML Schema。同樣需要Spring的ApplicationContext
實(shí)現(xiàn)作為IoC容器。Spring支持在簡單的BeanFactory
實(shí)現(xiàn)下使用dynamic-language-backed bean,但是你需要管理Spring內(nèi)部的種種細(xì)節(jié)。
關(guān)于XML Schema的配置,詳情請看附錄?A, XML Schema-based configuration 。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd"> <!-- this is the bean definition for the Groovy-backedMessenger
implementation --> <lang:groovy id="messenger" script-source="classpath:Messenger.groovy"> <lang:property name="message" value="I Can Do The Frug" /> </lang:groovy> <!-- an otherwise normal bean that will be injected by the Groovy-backedMessenger
--> <bean id="bookingService" class="x.y.DefaultBookingService"> <property name="messenger" ref="messenger" /> </bean> </beans>
現(xiàn)在可以象以前一樣使用bookingService
bean (DefaultBookingService
)的私有成員變量 messenger
,因?yàn)楸蛔⑷氲?code class="interfacename">Messenger實(shí)例確實(shí)是一個(gè)真正的Messenger
實(shí)例。這里也沒有什么特別的地方,就是簡單的Java和Groovy。
但愿你能夠無需多加說明就看明白以上的XML片段,而不用太擔(dān)心它是否恰當(dāng)或者是否正確。請繼續(xù)閱讀更深層次的細(xì)節(jié)以了解以上配置的原因。