?
This document uses PHP Chinese website manual Release
本章的大部分內(nèi)容的關(guān)注點都在描述Spring對動態(tài)語言的支持的細節(jié)上。在深入到這些細節(jié)之前,首先讓我們看一個使用動態(tài)語言定義的bean的快速上手的例子。第一個bean使用的動態(tài)語言是Groovy(這個例子來自Spring的測試套件,如果你打算看看對其他語言的支持的相同的例子,請閱讀相應(yīng)的源碼)。
下面是Groovy bean要實現(xiàn)的Messenger
接口。注意該接口是使用純Java定義的。依賴的對象是通過Messenger
接口的引用注入的,并不知道其實現(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實現(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
實現(xiàn)注入到DefaultBookingService
類的實例中。
要使用用戶定制的動態(tài)語言標簽來定義 dynamic-language-backed bean,需要在Spring XML配置文件的頭部添加相應(yīng)的XML Schema。同樣需要Spring的ApplicationContext
實現(xiàn)作為IoC容器。Spring支持在簡單的BeanFactory
實現(xiàn)下使用dynamic-language-backed bean,但是你需要管理Spring內(nèi)部的種種細節(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
,因為被注入的Messenger
實例確實是一個真正的Messenger
實例。這里也沒有什么特別的地方,就是簡單的Java和Groovy。
但愿你能夠無需多加說明就看明白以上的XML片段,而不用太擔心它是否恰當或者是否正確。請繼續(xù)閱讀更深層次的細節(jié)以了解以上配置的原因。