对于最新的稳定版本,请使用 Spring Framework 6.2.4! |
动态语言支持
Spring 为使用已 通过在 Spring 中使用动态语言(例如 Groovy)来定义。此支持允许 您可以使用支持的动态语言编写任意数量的类,并拥有 Spring 容器透明地实例化、配置和依赖注入生成的 对象。
Spring 的脚本支持主要针对 Groovy 和 BeanShell。超越这些 特别支持的语言,支持 JSR-223 脚本机制 用于与任何支持 JSR-223 的语言提供程序集成(从 Spring 4.2 开始), 例如 JRuby。
您可以找到有关此动态语言支持的完整工作示例 立即在 Scenarios 中有用。
第一个例子
本章的大部分内容是描述 细节。在深入研究动态语言支持的所有细节之前, 我们看一个用动态语言定义的 bean 的快速示例。动态 第一个 bean 的语言是 Groovy。(此示例的基础取自 Spring 测试套件。如果您想在任何其他 支持的语言,请查看源代码)。
下一个示例显示了Messenger
接口,Groovy bean 将要访问
实现。请注意,此接口是用纯 Java 定义的。依赖对象
注入了对Messenger
不知道底层的
implementation 是一个 Groovy 脚本。下面的清单显示了Messenger
接口:
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...
}
}
以下示例实现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 in file 'Messenger.groovy'
class GroovyMessenger implements Messenger {
String message
}
要使用自定义动态语言标记来定义动态语言支持的 bean,请使用
需要在 Spring XML 配置文件的顶部有 XML Schema 前导码。
您还需要使用 Spring 有关基于模式的配置的详细信息,请参 阅XML 基于模式的配置 。 |
最后,以下示例显示了影响
Groovy 定义Messenger
implementation 复制到DefaultBookingService
类:
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">
<!-- this is the bean definition for the Groovy-backed Messenger 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-backed Messenger -->
<bean id="bookingService" class="x.y.DefaultBookingService">
<property name="messenger" ref="messenger" />
</bean>
</beans>
这bookingService
bean (一个DefaultBookingService
) 现在可以使用其私有messenger
member 变量一样,因为Messenger
注入其中的实例是
一个Messenger
实例。这里没有什么特别的事情 — 只是普通的 Java 和
普通的 Groovy。
希望前面的 XML 代码段是不言自明的,但如果不是,请不要过分担心。 请继续阅读,深入了解上述配置的原因和原因。
定义由动态语言支持的 Bean
本节准确描述了如何在任何 支持的动态语言。
请注意,本章并不试图解释支持的 动态语言。例如,如果您想使用 Groovy 编写某些类 在您的应用程序中,我们假设您已经了解 Groovy。如果您需要更多详细信息 关于动态语言本身,请参阅 末尾的 更多资源 本章。
常见概念
使用动态语言支持的 bean 所涉及的步骤如下:
-
为动态语言源代码编写测试(自然)。
-
然后编写动态语言源代码本身。
-
使用适当的
<lang:language/>
元素(您可以通过 使用 Spring API,尽管您必须查阅 有关如何执行此作的说明,因为本章不介绍这种类型的高级配置)。 请注意,这是一个迭代步骤。每个动态至少需要一个 bean 定义 language 源文件(尽管多个 bean 定义可以引用同一个源文件)。
前两个步骤(测试和编写动态语言源文件)超出了范围 本章的范围。请参阅语言规范和参考手册 对于您选择的动态语言,并继续开发您的动态语言 源文件。不过,您首先要阅读本章的其余部分,因为 Spring 的动态语言支持确实对内容做了一些(小的)假设 的动态语言源文件。
<lang:language/> 元素
上一节列表中的最后一步涉及定义动态语言支持的 bean 定义,每个 bean 定义
想要配置(这与普通的 JavaBean 配置没有什么不同)。然而
而不是指定要
实例化和配置,您可以使用<lang:language/>
元素来定义动态语言支持的 Bean。
每种支持的语言都有相应的<lang:language/>
元素:
-
<lang:groovy/>
(时髦的) -
<lang:bsh/>
(BeanShell) -
<lang:std/>
(JSR-223,例如使用 JRuby)
可用于配置的确切属性和子元素取决于 确切地说,是用哪种语言定义 Bean(特定于语言的部分 本章稍后将详细介绍这一点)。
可刷新的 Bean
动态语言最引人注目的附加值之一(也许是唯一的) Spring 中的支持是“可刷新的 bean”功能。
可刷新 Bean 是动态语言支持的 Bean。用少量 configuration 中,动态语言支持的 bean 可以监视其底层 bean 中的更改 source file 资源,然后在动态语言源文件为 已更改(例如,当您在文件系统上编辑并保存对文件的更改时)。
这允许您将任意数量的动态语言源文件部署为 应用程序中,配置 Spring 容器以创建由动态 语言源文件(使用本章中介绍的机制)和(稍后的 随着需求的变化或其他一些外部因素的开始发挥作用)编辑一个动态 language 源文件,并且他们所做的任何更改都会反映在 Bean 中,即 由更改的动态语言源文件提供支持。无需关闭 正在运行的应用程序(如果是 Web 应用程序,则为 redeploy)。这 dynamic-language-supported bean so modified 从 更改了动态语言源文件。
默认情况下,此功能处于关闭状态。 |
现在我们可以看一个示例,看看开始使用 refreshable 是多么容易
豆。要打开可刷新 bean 功能,您必须指定一个
additional 属性<lang:language/>
元素中。所以
如果我们坚持前面的例子
本章,以下示例显示了我们将在 Spring XML 中更改的内容
配置以影响可刷新的 bean:
<beans>
<!-- this bean is now 'refreshable' due to the presence of the 'refresh-check-delay' attribute -->
<lang:groovy id="messenger"
refresh-check-delay="5000" <!-- switches refreshing on with 5 seconds between checks -->
script-source="classpath:Messenger.groovy">
<lang:property name="message" value="I Can Do The Frug" />
</lang:groovy>
<bean id="bookingService" class="x.y.DefaultBookingService">
<property name="messenger" ref="messenger" />
</bean>
</beans>
这真的就是你所要做的。这refresh-check-delay
在messenger
Bean 定义是 Bean 达到
刷新对基础动态语言源文件所做的任何更改。
您可以通过为refresh-check-delay
属性。请记住,默认情况下,刷新行为为
禁用。如果不需要刷新行为,请不要定义该属性。
如果我们随后运行以下应用程序,则可以执行可刷新功能。
(请原谅那些 “跳过圈子暂停执行 ”的恶作剧
在下一段代码中。这System.in.read()
call 只是为了让
程序的执行在您(本方案中的开发人员)离开时暂停
并编辑基础动态语言源文件,以便触发刷新
在动态语言支持的 bean 上。
下面的清单显示了这个示例应用程序:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
public final class Boot {
public static void main(final String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Messenger messenger = (Messenger) ctx.getBean("messenger");
System.out.println(messenger.getMessage());
// pause execution while I go off and make changes to the source file...
System.in.read();
System.out.println(messenger.getMessage());
}
}
Assume then, for the purposes of this example, that all calls to the getMessage()
method of Messenger
implementations have to be changed such that the message is
surrounded by quotation marks. The following listing shows the changes that you
(the developer) should make to the Messenger.groovy
source file when the
execution of the program is paused:
package org.springframework.scripting
class GroovyMessenger implements Messenger {
private String message = "Bingo"
public String getMessage() {
// change the implementation to surround the message in quotes
return "'" + this.message + "'"
}
public void setMessage(String message) {
this.message = message
}
}
When the program runs, the output before the input pause will be I Can Do The Frug
.
After the change to the source file is made and saved and the program resumes execution,
the result of calling the getMessage()
method on the dynamic-language-backed
Messenger
implementation is 'I Can Do The Frug'
(notice the inclusion of the
additional quotation marks).
Changes to a script do not trigger a refresh if the changes occur within the window of
the refresh-check-delay
value. Changes to the script are not actually picked up until
a method is called on the dynamic-language-backed bean. It is only when a method is
called on a dynamic-language-backed bean that it checks to see if its underlying script
source has changed. Any exceptions that relate to refreshing the script (such as
encountering a compilation error or finding that the script file has been deleted)
results in a fatal exception being propagated to the calling code.
The refreshable bean behavior described earlier does not apply to dynamic language
source files defined with the <lang:inline-script/>
element notation (see
Inline Dynamic Language Source Files). Additionally, it applies only to beans where
changes to the underlying source file can actually be detected (for example, by code
that checks the last modified date of a dynamic language source file that exists on the
file system).
Inline Dynamic Language Source Files
The dynamic language support can also cater to dynamic language source files that are
embedded directly in Spring bean definitions. More specifically, the
<lang:inline-script/>
element lets you define dynamic language source immediately
inside a Spring configuration file. An example might clarify how the inline script
feature works:
<lang:groovy id="messenger">
<lang:inline-script>
package org.springframework.scripting.groovy
import org.springframework.scripting.Messenger
class GroovyMessenger implements Messenger {
String message
}
</lang:inline-script>
<lang:property name="message" value="I Can Do The Frug" />
</lang:groovy>
If we put to one side the issues surrounding whether it is good practice to define
dynamic language source inside a Spring configuration file, the <lang:inline-script/>
element can be useful in some scenarios. For instance, we might want to quickly add a
Spring Validator
implementation to a Spring MVC Controller
. This is but a moment’s
work using inline source. (See Scripted Validators for such an
example.)
Understanding Constructor Injection in the Context of Dynamic-language-backed Beans
There is one very important thing to be aware of with regard to Spring’s dynamic
language support. Namely, you can not (currently) supply constructor arguments
to dynamic-language-backed beans (and, hence, constructor-injection is not available for
dynamic-language-backed beans). In the interests of making this special handling of
constructors and properties 100% clear, the following mixture of code and configuration
does not work:
An approach that cannot work
package org.springframework.scripting.groovy
import org.springframework.scripting.Messenger
// from the file 'Messenger.groovy'
class GroovyMessenger implements Messenger {
GroovyMessenger() {}
// this constructor is not available for Constructor Injection
GroovyMessenger(String message) {
this.message = message;
}
String message
String anotherMessage
}
<lang:groovy id="badMessenger"
script-source="classpath:Messenger.groovy">
<!-- this next constructor argument will not be injected into the GroovyMessenger -->
<!-- in fact, this isn't even allowed according to the schema -->
<constructor-arg value="This will not work" />
<!-- only property values are injected into the dynamic-language-backed object -->
<lang:property name="anotherMessage" value="Passed straight through to the dynamic-language-backed object" />
</lang>
In practice this limitation is not as significant as it first appears, since setter
injection is the injection style favored by the overwhelming majority of developers
(we leave the discussion as to whether that is a good thing to another day).
Groovy Beans
This section describes how to use beans defined in Groovy in Spring.
The Groovy homepage includes the following description:
“Groovy is an agile dynamic language for the Java 2 Platform that has many of the
features that people like so much in languages like Python, Ruby and Smalltalk, making
them available to Java developers using a Java-like syntax.”
If you have read this chapter straight from the top, you have already
seen an example of a Groovy-dynamic-language-backed
bean. Now consider another example (again using an example from the Spring test suite):
package org.springframework.scripting;
public interface Calculator {
int add(int x, int y);
}
The following example implements the Calculator
interface in Groovy:
package org.springframework.scripting.groovy
// from the file 'calculator.groovy'
class GroovyCalculator implements Calculator {
int add(int x, int y) {
x + y
}
}
The following bean definition uses the calculator defined in Groovy:
<!-- from the file 'beans.xml' -->
<beans>
<lang:groovy id="calculator" script-source="classpath:calculator.groovy"/>
</beans>
Finally, the following small application exercises the preceding configuration:
package org.springframework.scripting;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Calculator calc = ctx.getBean("calculator", Calculator.class);
System.out.println(calc.add(2, 8));
}
}
The resulting output from running the above program is (unsurprisingly) 10
.
(For more interesting examples, see the dynamic language showcase project for a more
complex example or see the examples Scenarios later in this chapter).
You must not define more than one class per Groovy source file. While this is perfectly
legal in Groovy, it is (arguably) a bad practice. In the interests of a consistent
approach, you should (in the opinion of the Spring team) respect the standard Java
conventions of one (public) class per source file.
Customizing Groovy Objects by Using a Callback
The GroovyObjectCustomizer
interface is a callback that lets you hook additional
creation logic into the process of creating a Groovy-backed bean. For example,
implementations of this interface could invoke any required initialization methods,
set some default property values, or specify a custom MetaClass
. The following listing
shows the GroovyObjectCustomizer
interface definition:
public interface GroovyObjectCustomizer {
void customize(GroovyObject goo);
}
The Spring Framework instantiates an instance of your Groovy-backed bean and then
passes the created GroovyObject
to the specified GroovyObjectCustomizer
(if one
has been defined). You can do whatever you like with the supplied GroovyObject
reference. We expect that most people want to set a custom MetaClass
with this
callback, and the following example shows how to do so:
public final class SimpleMethodTracingCustomizer implements GroovyObjectCustomizer {
public void customize(GroovyObject goo) {
DelegatingMetaClass metaClass = new DelegatingMetaClass(goo.getMetaClass()) {
public Object invokeMethod(Object object, String methodName, Object[] arguments) {
System.out.println("Invoking '" + methodName + "'.");
return super.invokeMethod(object, methodName, arguments);
}
};
metaClass.initialize();
goo.setMetaClass(metaClass);
}
}
A full discussion of meta-programming in Groovy is beyond the scope of the Spring
reference manual. See the relevant section of the Groovy reference manual or do a
search online. Plenty of articles address this topic. Actually, making use of a
GroovyObjectCustomizer
is easy if you use the Spring namespace support, as the
following example shows:
<!-- define the GroovyObjectCustomizer just like any other bean -->
<bean id="tracingCustomizer" class="example.SimpleMethodTracingCustomizer"/>
<!-- ... and plug it into the desired Groovy bean via the 'customizer-ref' attribute -->
<lang:groovy id="calculator"
script-source="classpath:org/springframework/scripting/groovy/Calculator.groovy"
customizer-ref="tracingCustomizer"/>
If you do not use the Spring namespace support, you can still use the
GroovyObjectCustomizer
functionality, as the following example shows:
<bean id="calculator" class="org.springframework.scripting.groovy.GroovyScriptFactory">
<constructor-arg value="classpath:org/springframework/scripting/groovy/Calculator.groovy"/>
<!-- define the GroovyObjectCustomizer (as an inner bean) -->
<constructor-arg>
<bean id="tracingCustomizer" class="example.SimpleMethodTracingCustomizer"/>
</constructor-arg>
</bean>
<bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/>
You may also specify a Groovy CompilationCustomizer
(such as an ImportCustomizer
)
or even a full Groovy CompilerConfiguration
object in the same place as Spring’s
GroovyObjectCustomizer
. Furthermore, you may set a common GroovyClassLoader
with custom
configuration for your beans at the ConfigurableApplicationContext.setClassLoader
level;
this also leads to shared GroovyClassLoader
usage and is therefore recommendable in case of
a large number of scripted beans (avoiding an isolated GroovyClassLoader
instance per bean).
BeanShell Beans
This section describes how to use BeanShell beans in Spring.
The BeanShell homepage includes the following
description:
BeanShell is a small, free, embeddable Java source interpreter with dynamic language
features, written in Java. BeanShell dynamically runs standard Java syntax and
extends it with common scripting conveniences such as loose types, commands, and method
closures like those in Perl and JavaScript.
In contrast to Groovy, BeanShell-backed bean definitions require some (small) additional
configuration. The implementation of the BeanShell dynamic language support in Spring is
interesting, because Spring creates a JDK dynamic proxy that implements all of the
interfaces that are specified in the script-interfaces
attribute value of the
<lang:bsh>
element (this is why you must supply at least one interface in the value
of the attribute, and, consequently, program to interfaces when you use BeanShell-backed
beans). This means that every method call on a BeanShell-backed object goes through the
JDK dynamic proxy invocation mechanism.
Now we can show a fully working example of using a BeanShell-based bean that implements
the Messenger
interface that was defined earlier in this chapter. We again show the
definition of the Messenger
interface:
package org.springframework.scripting;
public interface Messenger {
String getMessage();
}
The following example shows the BeanShell “implementation” (we use the term loosely here)
of the Messenger
interface:
String message;
String getMessage() {
return message;
}
void setMessage(String aMessage) {
message = aMessage;
}
The following example shows the Spring XML that defines an “instance” of the above
“class” (again, we use these terms very loosely here):
<lang:bsh id="messageService" script-source="classpath:BshMessenger.bsh"
script-interfaces="org.springframework.scripting.Messenger">
<lang:property name="message" value="Hello World!" />
</lang:bsh>
See Scenarios for some scenarios where you might want to use
BeanShell-based beans.
Scenarios
The possible scenarios where defining Spring managed beans in a scripting language would
be beneficial are many and varied. This section describes two possible use cases for the
dynamic language support in Spring.
Scripted Spring MVC Controllers
One group of classes that can benefit from using dynamic-language-backed beans is that
of Spring MVC controllers. In pure Spring MVC applications, the navigational flow
through a web application is, to a large extent, determined by code encapsulated within
your Spring MVC controllers. As the navigational flow and other presentation layer logic
of a web application needs to be updated to respond to support issues or changing
business requirements, it may well be easier to effect any such required changes by
editing one or more dynamic language source files and seeing those changes being
immediately reflected in the state of a running application.
Remember that, in the lightweight architectural model espoused by projects such as
Spring, you typically aim to have a really thin presentation layer, with all
the meaty business logic of an application being contained in the domain and service
layer classes. Developing Spring MVC controllers as dynamic-language-backed beans lets
you change presentation layer logic by editing and saving text files. Any
changes to such dynamic language source files is (depending on the configuration)
automatically reflected in the beans that are backed by dynamic language source files.
To effect this automatic “pickup” of any changes to dynamic-language-backed
beans, you have to enable the “refreshable beans” functionality. See
Refreshable Beans for a full treatment of this feature.
The following example shows an org.springframework.web.servlet.mvc.Controller
implemented
by using the Groovy dynamic language:
package org.springframework.showcase.fortune.web
import org.springframework.showcase.fortune.service.FortuneService
import org.springframework.showcase.fortune.domain.Fortune
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.mvc.Controller
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
// from the file '/WEB-INF/groovy/FortuneController.groovy'
class FortuneController implements Controller {
@Property FortuneService fortuneService
ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse httpServletResponse) {
return new ModelAndView("tell", "fortune", this.fortuneService.tellFortune())
}
}
<lang:groovy id="fortune"
refresh-check-delay="3000"
script-source="/WEB-INF/groovy/FortuneController.groovy">
<lang:property name="fortuneService" ref="fortuneService"/>
</lang:groovy>
Scripted Validators
Another area of application development with Spring that may benefit from the
flexibility afforded by dynamic-language-backed beans is that of validation. It can
be easier to express complex validation logic by using a loosely typed dynamic language
(that may also have support for inline regular expressions) as opposed to regular Java.
Again, developing validators as dynamic-language-backed beans lets you change
validation logic by editing and saving a simple text file. Any such changes is
(depending on the configuration) automatically reflected in the execution of a
running application and would not require the restart of an application.
To effect the automatic “pickup” of any changes to dynamic-language-backed
beans, you have to enable the 'refreshable beans' feature. See
Refreshable Beans for a full and detailed treatment of this feature.
The following example shows a Spring org.springframework.validation.Validator
implemented by using the Groovy dynamic language (see Validation using Spring’s Validator interface
for a discussion of the
Validator
interface):
import org.springframework.validation.Validator
import org.springframework.validation.Errors
import org.springframework.beans.TestBean
class TestBeanValidator implements Validator {
boolean supports(Class clazz) {
return TestBean.class.isAssignableFrom(clazz)
}
void validate(Object bean, Errors errors) {
if(bean.name?.trim()?.size() > 0) {
return
}
errors.reject("whitespace", "Cannot be composed wholly of whitespace.")
}
}
Additional Details
This last section contains some additional details related to the dynamic language support.
AOP — Advising Scripted Beans
You can use the Spring AOP framework to advise scripted beans. The Spring AOP
framework actually is unaware that a bean that is being advised might be a scripted
bean, so all of the AOP use cases and functionality that you use (or aim to use)
work with scripted beans. When you advise scripted beans, you cannot use class-based
proxies. You must use interface-based proxies.
You are not limited to advising scripted beans. You can also write aspects themselves
in a supported dynamic language and use such beans to advise other Spring beans.
This really would be an advanced use of the dynamic language support though.
Scoping
In case it is not immediately obvious, scripted beans can be scoped in the same way as
any other bean. The scope
attribute on the various <lang:language/>
elements lets
you control the scope of the underlying scripted bean, as it does with a regular
bean. (The default scope is singleton,
as it is with “regular” beans.)
The following example uses the scope
attribute to define a Groovy bean scoped as
a prototype:
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="messenger" script-source="classpath:Messenger.groovy" scope="prototype">
<lang:property name="message" value="I Can Do The RoboCop" />
</lang:groovy>
<bean id="bookingService" class="x.y.DefaultBookingService">
<property name="messenger" ref="messenger" />
</bean>
</beans>
See Bean Scopes in The IoC Container
for a full discussion of the scoping support in the Spring Framework.
The lang
XML schema
The lang
elements in Spring XML configuration deal with exposing objects that have been
written in a dynamic language (such as Groovy or BeanShell) as beans in the Spring container.
These elements (and the dynamic language support) are comprehensively covered in
Dynamic Language Support. See that section
for full details on this support and the lang
elements.
To use the elements in the lang
schema, you need to have the following preamble at the
top of your Spring XML configuration file. The text in the following snippet references
the correct schema so that the tags in the lang
namespace are available to you:
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">
<!-- bean definitions here -->
</beans>