Spring 2.0 引入動態語言支援,將框架從 Java 中心擴展為 JVM 中心,讓 Groovy、JRuby、BeanShell 等語言無縫融入 IoC、AOP 等核心機制。本文詳述 Groovy Bean 的多種配置方式與使用場景,為後續進階特性奠基。
Groovy 是專為 JVM 設計的敏捷動態語言,繼承 Java 強大生態,融合 Python、Ruby、Smalltalk 的閉包、動態類型、元編程特性,語法對 Java 開發者極其友好,互操作零門檻。
groovyc 編譯為 .class,配置同普通 Java Bean。傳統 XML 或 Spring 2.5+ 註解均適用:
<bean id="pdfGenerator" class="groovierspring.GroovyPdfGenerator">
<property name="companyName" value="Groovy Bookstore"/>
</bean>
@Component("pdfGenerator")
class GroovyPdfGenerator implements PdfGenerator { ... }
定義工廠 Bean 指向腳本路徑,後處理器替換為實際實例:
<bean id="pdfGenerator" class="org.springframework.scripting.groovy.GroovyScriptFactory">
<constructor-arg value="classpath:groovierspring/GroovyPdfGenerator.groovy"/>
<property name="companyName" value="Groovier Bookstore"/>
</bean>
<bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/>
.groovy 檔可包含多個類並根據條件返回實例:
class SimpleGroovyPdfGenerator implements PdfGenerator { ... }
class ComplexGroovyPdfGenerator implements PdfGenerator { ... }
def type = System.properties['generatorType']
if (type == 'simple') return new SimpleGroovyPdfGenerator()
else return new ComplexGroovyPdfGenerator()
<lang:groovy id="pdfGenerator" script-source="classpath:groovierspring/GroovyPdfGenerator.groovy">
<lang:property name="companyName" value="Really Groovy Bookstore"/>
</lang:groovy>
意圖清晰,自動處理後處理器註冊。
以 Groovy DSL 定義 Bean,支援邏輯嵌入:
def builder = new grails.spring.BeanBuilder()
builder.beans {
pdfGenerator(GroovyPdfGenerator) { companyName = 'Compiled BeanBuilder Bookstore' }
pdfGenerator(GroovyScriptFactory, 'classpath:.../GroovyPdfGenerator.groovy') { companyName = 'Scripted BeanBuilder Bookstore' }
scriptFactoryPostProcessor(ScriptFactoryPostProcessor)
}
def appContext = builder.createApplicationContext()
依賴注入、AOP 等 Spring 特性無感知適用:
@Service
public class InvoicePdfServiceImpl implements InvoicePdfService {
@Autowired private PdfGenerator pdfGenerator;
public byte[] generatePdf(Long invoiceId) {
return pdfGenerator.pdfFor(getInvoiceSomehow(invoiceId));
}
}
實現語言對服務調用者完全隱藏,實現鬆耦合與易測試性。
<lang:groovy> 配置腳本。下一篇將深入探討 Spring 最引人注目的動態特性:運行時監測腳本變更並自動重載 Bean,打破靜態部署的桎梏。