Dynamic Language Support
Spring 的脚本支持主要针对 Groovy 和 BeanShell。除了这些特定支持的语言之外,JSR-223 脚本机制还支持与任何 JSR-223 可执行语言提供程序的集成,例如 JRuby。
Spring 针对使用动态语言(例如 Groovy)定义的类和对象提供全面的支持。利用此支持,你可以在受支持的动态语言中编写任意数量的类,Spring 容器会透明地实例化、配置以及对生成的对象进行依赖注入。
Spring provides comprehensive support for using classes and objects that have been defined by using a dynamic language (such as Groovy) with Spring. This support lets you write any number of classes in a supported dynamic language and have the Spring container transparently instantiate, configure, and dependency inject the resulting objects.
Spring 的脚本支持主要针对 Groovy 和 BeanShell。除了这些专门受支持的语言之外,JSR-223 脚本机制还支持与任何 JSR-223 可执行语言提供程序的集成(截至 Spring 4.2),例如 JRuby。
Spring’s scripting support primarily targets Groovy and BeanShell. Beyond those specifically supported languages, the JSR-223 scripting mechanism is supported for integration with any JSR-223 capable language provider (as of Spring 4.2), e.g. JRuby.
你可以在 Scenarios 中找到此动态语言支持立即可用的完整工作示例。
You can find fully working examples of where this dynamic language support can be immediately useful in Scenarios.
A First Example
本章的重点主要在于详细描述动态语言支持。在深入讨论动态语言支持的方方面面之前,让我们先来看一个使用动态语言定义的 bean 的快速示例。此第一个 bean 的动态语言是 Groovy。(此示例的基础取自 Spring 测试套件。如果你想要查看任何其他受支持语言中的等效示例,请查看源代码)。
The bulk of this chapter is concerned with describing the dynamic language support in detail. Before diving into all of the ins and outs of the dynamic language support, we look at a quick example of a bean defined in a dynamic language. The dynamic language for this first bean is Groovy. (The basis of this example was taken from the Spring test suite. If you want to see equivalent examples in any of the other supported languages, take a look at the source code).
下一个示例显示了 Groovy bean 将实现的 Messenger
接口。请注意,此接口在纯 Java 中定义。已通过对 Messenger
的引用注入的依赖对象并不知道底层实现是一种 Groovy 脚本。以下列表显示了 Messenger
接口:
The next example shows the Messenger
interface, which the Groovy bean is going to
implement. Note that this interface is defined in plain Java. Dependent objects that
are injected with a reference to the Messenger
do not know that the underlying
implementation is a Groovy script. The following listing shows the Messenger
interface:
public interface Messenger {
String getMessage();
}
下列示例定义了一个依赖 Messenger
接口的类:
The following example defines a class that has a dependency on the Messenger
interface:
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 中实现了 Messenger
接口:
The following example implements the Messenger
interface in 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 To use the custom dynamic language tags to define dynamic-language-backed beans, you
need to have the XML Schema preamble at the top of your Spring XML configuration file.
You also need to use a Spring 有关基于模式的配置的更多信息,请参阅 XML Schema-based Configuration。 For more information on schema-based configuration, see XML Schema-based Configuration . |
最后,下列示例显示了用来将 Groovy 定义的 Messenger
实现注入 DefaultBookingService
类的实例中的 bean 定义:
Finally, the following example shows the bean definitions that effect the injection of the
Groovy-defined Messenger
implementation into an instance of the
DefaultBookingService
class:
<?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
成员变量,就像对正常的 Messenger
实例那样,因为注入其中的 Messenger
实例是一个 Messenger
实例。这里没有发生任何特殊的事情——只有普通的 Java 和普通的 Groovy。
The bookingService
bean (a DefaultBookingService
) can now use its private messenger
member variable as normal, because the Messenger
instance that was injected into it is
a Messenger
instance. There is nothing special going on here — just plain Java and
plain Groovy.
我们希望前面的 XML 片段不言自明,但如果你感到一头雾水,也不必过于担心。继续阅读,深入详细了解上述配置的原因和方式。
Hopefully, the preceding XML snippet is self-explanatory, but do not worry unduly if it is not. Keep reading for the in-depth detail on the whys and wherefores of the preceding configuration.
Defining Beans that Are Backed by Dynamic Languages
本节准确地描述了您如何在任何受支持的动态语言中定义由 Spring 管理的 bean。
This section describes exactly how you define Spring-managed beans in any of the supported dynamic languages.
请注意,本章不会尝试解释所支持的动态语言的语法和习语。例如,如果您想用 Groovy 来编写应用程序中某些类,那么我们会认为您已经了解 Groovy。如果您需要了解动态语言本身的更多详细信息,请参阅本章末尾处的 Further Resources。
Note that this chapter does not attempt to explain the syntax and idioms of the supported dynamic languages. For example, if you want to use Groovy to write certain of the classes in your application, we assume that you already know Groovy. If you need further details about the dynamic languages themselves, see Further Resources at the end of this chapter.
Common Concepts
使用动态语言支持的 bean 所涉及的步骤如下:
The steps involved in using dynamic-language-backed beans are as follows:
-
Write the test for the dynamic language source code (naturally).
-
Then write the dynamic language source code itself.
-
Define your dynamic-language-backed beans by using the appropriate
<lang:language/>
element in the XML configuration (you can define such beans programmatically by using the Spring API, although you will have to consult the source code for directions on how to do this, as this chapter does not cover this type of advanced configuration). Note that this is an iterative step. You need at least one bean definition for each dynamic language source file (although multiple bean definitions can reference the same source file).
前两个步骤(测试和编写动态语言源文件)超出了本章的范围。请参阅您选择的动态语言的语言规范和参考手册,并着手开发您的动态语言源文件。不过,您首先需要阅读本章的其余部分,因为 Spring 的动态语言支持对您的动态语言源文件的内容做了一些(少量)假设。
The first two steps (testing and writing your dynamic language source files) are beyond the scope of this chapter. See the language specification and reference manual for your chosen dynamic language and crack on with developing your dynamic language source files. You first want to read the rest of this chapter, though, as Spring’s dynamic language support does make some (small) assumptions about the contents of your dynamic language source files.
The <lang:language/> element
preceding section 中列出的步骤的最后一步涉及定义动态语言支持的 Bean 定义,每个您想要配置的 Bean 一个(这与普通的 JavaBean 配置没有什么不同)。然而,您不一定要指定要由容器实例化和配置的类的完全限定类名,您可以使用 <lang:language/>
元素来定义动态语言支持的 Bean。
The final step in the list in the preceding section
involves defining dynamic-language-backed bean definitions, one for each bean that you
want to configure (this is no different from normal JavaBean configuration). However,
instead of specifying the fully qualified class name of the class that is to be
instantiated and configured by the container, you can use the <lang:language/>
element to define the dynamic language-backed bean.
每种受支持的语言都有相应的 <lang:language/>
元素:
Each of the supported languages has a corresponding <lang:language/>
element:
-
<lang:groovy/>
(Groovy) -
<lang:bsh/>
(BeanShell) -
<lang:std/>
(JSR-223, e.g. with JRuby)
可用于配置的確切屬性和子元素取決於該 bean 已在哪種語言中被定義(本章後續的特定語言部分對此進行了詳細說明)。
The exact attributes and child elements that are available for configuration depends on exactly which language the bean has been defined in (the language-specific sections later in this chapter detail this).
Refreshable Beans
Spring 中动态语言支持最引人注目的一个(或许是唯一一个)增值功能是“可刷新 bean”特性。
One of the (and perhaps the single) most compelling value adds of the dynamic language support in Spring is the “refreshable bean” feature.
可刷新 bean 是以动态语言为后盾的 bean。通过少量配置,以动态语言为后盾的 bean 可以监视其底层源文件资源的变化,然后在动态语言源文件更改时重新加载自身(例如,当您在文件系统上编辑和保存对该文件的更改时)。
A refreshable bean is a dynamic-language-backed bean. With a small amount of configuration, a dynamic-language-backed bean can monitor changes in its underlying source file resource and then reload itself when the dynamic language source file is changed (for example, when you edit and save changes to the file on the file system).
这使您可以将任意数量的动态语言源文件作为应用程序的一部分进行部署,配置 Spring 容器以使用动态语言源文件(使用本章中描述的机制)创建由其作为后盾的 bean,并且(稍后,随着需求发生变化或其他外部因素出现)编辑动态语言源文件并让所做的任何更改反映在由已更改的动态语言源文件作为后盾的 bean 中。无需关闭正在运行的应用程序(或者如果是 Web 应用程序的话无需重新部署)。以动态语言作为后盾的 bean 可以从已更改的动态语言源文件中获取新状态和逻辑。
This lets you deploy any number of dynamic language source files as part of an application, configure the Spring container to create beans backed by dynamic language source files (using the mechanisms described in this chapter), and (later, as requirements change or some other external factor comes into play) edit a dynamic language source file and have any change they make be reflected in the bean that is backed by the changed dynamic language source file. There is no need to shut down a running application (or redeploy in the case of a web application). The dynamic-language-backed bean so amended picks up the new state and logic from the changed dynamic language source file.
此功能默认关闭。 |
This feature is off by default. |
现在,我们来看一个示例,看看使用可刷新 Bean 开始有多么容易。要启用可刷新 Bean 功能,您必须在 Bean 定义的 <lang:language/>
元素上指定一个额外的属性。因此,如果我们坚持使用本章前面部分的 the example,下面的示例展示了我们会更改 Spring XML 配置以实现可刷新 Bean 的内容:
Now we can take a look at an example to see how easy it is to start using refreshable
beans. To turn on the refreshable beans feature, you have to specify exactly one
additional attribute on the <lang:language/>
element of your bean definition. So,
if we stick with the example from earlier in
this chapter, the following example shows what we would change in the Spring XML
configuration to effect refreshable beans:
<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>
这真的是您要做的所有事情。messenger
bean 定义上定义的 refresh-check-delay
属性是在对底层动态语言源文件进行任何更改之后刷新 bean 的毫秒数。您可以通过将负值分配给 refresh-check-delay
属性来关闭刷新行为。请记住,刷新行为在默认情况下处于禁用状态。如果您不想要刷新行为,请不要定义该属性。
That really is all you have to do. The refresh-check-delay
attribute defined on the
messenger
bean definition is the number of milliseconds after which the bean is
refreshed with any changes made to the underlying dynamic language source file.
You can turn off the refresh behavior by assigning a negative value to the
refresh-check-delay
attribute. Remember that, by default, the refresh behavior is
disabled. If you do not want the refresh behavior, do not define the attribute.
如果我们随后运行以下应用程序,我们就可以使用可刷新特性。(在下一段代码中,请忽略“采取预防措施来暂停执行”的把戏。)System.in.read()
调用仅出现在此,以便在您(本场景中的开发人员)关闭并编辑底层动态语言源文件并让程序恢复执行时可刷新触发器对以动态语言作为后盾的 bean 产生影响时暂停程序执行。
If we then run the following application, we can exercise the refreshable feature.
(Please excuse the “jumping-through-hoops-to-pause-the-execution” shenanigans
in this next slice of code.) The System.in.read()
call is only there so that the
execution of the program pauses while you (the developer in this scenario) go off
and edit the underlying dynamic language source file so that the refresh triggers
on the dynamic-language-backed bean when the program resumes execution.
以下列表显示了此示例应用程序:
The following listing shows this sample application:
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());
}
}
然后,对于本示例的目的,假设对 Messenger
实现的 getMessage()
方法的所有调用都必须更改,以便消息被引号包围。以下列表显示了当程序执行暂停时,您(开发人员)应当对 Messenger.groovy
源文件所做的更改:
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:
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
}
}
当程序运行时,输入暂停前的输出为 I Can Do The Frug
。在对源文件进行了更改并保存,且程序恢复执行之后,调用以动态语言作为后盾的 Messenger
实现上的 getMessage()
方法的结果为 ‘I Can Do The Frug’(请注意引入了附加的引号)。
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).
如果更改发生在 refresh-check-delay
值窗口内,则脚本的更改不会触发刷新。只有对以动态语言作为后盾的 bean 调用方法时,才会实际获取脚本的更改。只有当对以动态语言作为后盾的 bean 调用方法时,它才会检查其底层脚本源是否已更改。与刷新脚本相关的任何异常(例如遇到编译错误或发现脚本文件已被删除)都会导致致命的异常传播到调用代码。
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.
前面描述的可刷新 Bean 行为不适用于用 <lang:inline-script/>
元素符号定义的动态语言源文件(请参阅Inline Dynamic Language Source Files)。此外,它只适用于发生更改时的基础源文件实际上可以检测到的 Bean(例如,通过代码来检查文件系统中存在的动态语言源文件的最后修改日期)。
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
动态语言支持还可以满足直接嵌入 Spring bean 定义中的动态语言源文件。更具体地说,<lang:inline-script/>
元素使您能够直接在 Spring 配置文件中定义动态语言源。一个示例可能会解释内联脚本特性如何工作:
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>
如果我们暂且将这个问题放在一边,即在 Spring 配置文件中定义动态语言源是不是良好的实践, <lang:inline-script/>
元素在某些情况下会很有用。例如,我们可能想快速向 Spring MVC Controller
添加一个 Spring Validator
实现。使用内联源,这只是一瞬间的事情。(请参阅 Scripted Validators 以获取此类示例。)
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
有一件非常重要的事情需要了解,即 Spring 的动态语言支持。即,你不能(目前)为动态语言支持的 bean 提供构造函数参数(因此,动态语言支持的 bean 不可使用构造函数注入)。为了使这种对构造函数和属性的特殊处理 100% 清晰,以下代码和配置混合不起作用:
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:
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>
在实践中,这一限制并不像乍看起来那么明显,因为 setter 注入是绝大多数开发者所偏爱的注入风格(我们暂且不去讨论这是否是件好事)。
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
本节介绍如何在 Spring 中使用 Groovy 中定义的 bean。
This section describes how to use beans defined in Groovy in Spring.
Groovy 主页包含以下描述:
The Groovy homepage includes the following description:
“Groovy 是一款 dành cho Java 2 Platform 的敏捷动态语言,具备 Python、Ruby 和 Smalltalk 等语言中很多深受人们青睐的特性,让 Java 开发者可以使用 Java 式语法利用这些特性。”
“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.”
如果您已经从头到尾阅读了本章,您已经 seen an example Groovy 动态语言支持的 Bean。现在考虑另一个示例(同样使用 Spring 测试套件中的示例):
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):
public interface Calculator {
int add(int x, int y);
}
以下示例在 Groovy 中实现了 Calculator
接口:
The following example implements the Calculator
interface in Groovy:
// from the file 'calculator.groovy'
class GroovyCalculator implements Calculator {
int add(int x, int y) {
x + y
}
}
以下 bean 定义使用在 Groovy 中定义的计算器:
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:
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));
}
}
运行上述程序产生的结果(不出所料)是 10
。(有关更有趣的示例,请参阅动态语言展示项目,以了解更复杂的示例,或者稍后在本章中查看示例 Scenarios)。
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).
你不能在每个 Groovy 源文件中定义多个类。虽然这在 Groovy 中完全合法,但(可以说)是一种不良做法。为了保持方法一致,你应该(Spring 团队认为)遵守每个源文件一个(公共)类的标准 Java 惯例。
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
GroovyObjectCustomizer
接口是一种回调,允许你将附加的创建逻辑挂接到创建 Groovy 支持的 bean 的过程中。例如,此接口的实现可以调用任何必需的初始化方法,设置一些默认属性值,或指定一个自定义 MetaClass
。以下列表显示了 GroovyObjectCustomizer
接口定义:
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);
}
Spring 框架实例化你的 Groovy 支持的 bean,然后将创建的 GroovyObject
传递到指定的 GroovyObjectCustomizer
中(如果已定义)。你可以使用提供的 GroovyObject
引用执行任何你想要的操作。我们预计大多数人都想使用此回调设置一个自定义 MetaClass
,以下示例展示了如何执行此操作:
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);
}
}
在 Groovy 中进行元编程的完整讨论超出了 Spring 参考手册的范围。请参阅 Groovy 参考手册的相关部分或在线搜索。大量文章都讨论了这个主题。事实上,如果你使用 Spring 名称空间支持,则使用 GroovyObjectCustomizer
非常容易,如下例所示:
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"/>
如果你不使用 Spring 名称空间支持,仍然可以使用 GroovyObjectCustomizer
功能,如下例所示:
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"/>
你还可以指定 Groovy |
You may also specify a Groovy |
BeanShell Beans
本节介绍如何在 Spring 中使用 BeanShell Bean。
This section describes how to use BeanShell beans in Spring.
BeanShell homepage包括以下说明:
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.
与 Groovy 不同,BeanShell 支持的 bean 定义需要一些(少量的)额外配置。Spring 中 BeanShell 动态语言支持的实现很有意思,因为 Spring 创建一个实现 <lang:bsh>
元素的 script-interfaces
属性值中指定的所有接口的 JDK 动态代理(这就是为什么你必须在属性的值中至少提供一个接口,并且因此在你使用 BeanShell 支持的 bean 时必须针对接口进行编程)。这意味着对 BeanShell 支持的对象进行的每一方法调用都会经过 JDK 动态代理调用机制。
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.
现在,我们可以展示一个使用基于 BeanShell 的 bean 的完整工作示例,该 bean 可实现本章前面定义的 Messenger
接口。我们再次展示 Messenger
接口的定义:
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:
public interface Messenger {
String getMessage();
}
以下示例展示了 Messenger
接口的 BeanShell “实现”(此处我们宽泛地使用这一术语):
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;
}
以下示例展示了定义上述“类”的 Spring XML(再次说一下,此处我们非常宽泛地使用这些术语):
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>
请参见 Scenarios,了解您可能想要使用基于 BeanShell 的 Bean 的一些场景。
See Scenarios for some scenarios where you might want to use BeanShell-based beans.
Scenarios
在脚本语言中定义 Spring 托管的 bean 可能有益的可能情形多种多样。本节介绍了 Spring 中动态语言支持的两个可能用例。
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
可以从使用动态语言支持的 bean 中受益的一组类是 Spring MVC 控制器。在纯 Spring MVC 应用程序中,通过 Web 应用程序的导航流程在很大程度上是由 Spring MVC 控制器中封装的代码决定的。由于 Web 应用程序的导航流程和其他表示层逻辑需要更新才能响应支持问题或不断变化的业务需求,因此通过编辑一个或多个动态语言源文件,并将这些更改立即反映在正在运行的应用程序的状态中,可能更容易进行任何此类所需更改。
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.
请记住,在 Spring 等项目提倡的轻量级架构模型中,您通常的目标是拥有一个非常精简的表示层,应用程序的所有重要业务逻辑都包含在域和服务层类中。将 Spring MVC 控制器开发为动态语言支持的 bean 可让您通过编辑和保存文本文件来更改表示层逻辑。对任何此类动态语言源文件的更改(取决于配置)都会自动反映在由动态语言源文件支持的 bean 中。
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.
要执行动态语言后备 bean 的任何更改的自动 “pickup”,你必须启用 “refreshable beans” 功能。有关此功能的完整处理,请参见 Refreshable Beans。 |
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. |
以下示例展示了一个使用 Groovy 动态语言实现的 org.springframework.web.servlet.mvc.Controller
:
The following example shows an org.springframework.web.servlet.mvc.Controller
implemented
by using the Groovy dynamic language:
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
Spring 中的另一个应用程序开发领域可能受益于动态语言支持的灵活性的是验证。与普通 Java 相比,使用松散类型动态语言(它可能还支持内联正则表达式)可以更容易地表达复杂的验证逻辑。
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.
同样,将验证器开发为动态语言支持的 bean 可让您通过编辑和保存一个简单的文本文件来更改验证逻辑。任何此类更改(取决于配置)都会自动反映在正在运行的应用程序的执行中,并且不需要重新启动应用程序。
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.
要执行动态语言后备 bean 的任何更改的自动 “pickup”,你必须启用“可刷新 bean”功能。有关此功能的完整且详细的处理,请参见 Refreshable Beans。 |
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. |
以下示例展示了使用 Groovy 动态语言实现的 Spring org.springframework.validation.Validator
(请参阅 Validation using Spring’s Validator interface以了解`Validator`接口的说明):
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
您可以使用 Spring AOP 框架通知脚本 Bean。Spring AOP 框架实际上不知道要通知的 Bean 可能是一个脚本 Bean,因此您使用(或打算使用)的所有 AOP 用例和功能都可以与脚本 Bean 配合使用。当您通知脚本 Bean 时,您无法使用基于类的代理。您必须使用 interface-based proxies。
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.
您不限于建议脚本 bean。您还可以使用支持的动态语言编写切面本身,并使用此类 bean 建议其他 Spring bean。但这实际上将是对动态语言支持的深入使用。
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
如果没有立即显而易见,则脚本 Bean 可以像任何其他 Bean 一样设置范围。各个 <lang:language/>
元素上的 scope
属性可以让您控制基础脚本 Bean 的范围,就像它控制常规 Bean 的范围一样。(默认范围为 singleton,与 “regular” Bean 的默认范围一样。)
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.)
以下示例使用 scope
属性将 Groovy Bean 设置为具有 prototype 范围:
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>
请参见 The IoC Container 中的 Bean Scopes,以全面了解 Spring Framework 中的范围支持。
See Bean Scopes in The IoC Container for a full discussion of the scoping support in the Spring Framework.
The lang
XML schema
Spring XML 配置中的 lang
元素用于将动态语言(如 Groovy 或 BeanShell)编写的对象作为 Spring 容器中的 bean 公开。
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.
Dynamic Language Support中全面介绍了这些元素(以及动态语言支持)。请参阅该部分以全面了解此支持及 `lang`元素。
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.
要使用 lang
模式中的元素,需要在 Spring XML 配置文件的顶部有如下的前导内容。以下代码片段中的文本引用了正确的模式,以便向你提供 lang
命名空间中的标记:
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>