Spring-Framework - Optimize - Chapter 8. Language Support
Spring-Framework - Optimize - Chapter 8. Language Support
Language Support
8.1. Kotlin
Kotlin is a statically typed language that targets the JVM (and other platforms) which allows writing
concise and elegant code while providing very good interoperability with existing libraries written
in Java.
The Spring Framework provides first-class support for Kotlin and lets developers write Kotlin
applications almost as if the Spring Framework was a native Kotlin framework. Most of the code
samples of the reference documentation are provided in Kotlin in addition to Java.
The easiest way to build a Spring application with Kotlin is to leverage Spring Boot and its dedicated
Kotlin support. This comprehensive tutorial will teach you how to build Spring Boot applications
with Kotlin using start.spring.io.
Feel free to join the #spring channel of Kotlin Slack or ask a question with spring and kotlin as tags
on Stackoverflow if you need support.
8.1.1. Requirements
Spring Framework supports Kotlin 1.3+ and requires kotlin-stdlib (or one of its variants, such as
kotlin-stdlib-jdk8) and kotlin-reflect to be present on the classpath. They are provided by default
if you bootstrap a Kotlin project on start.spring.io.
The Jackson Kotlin module is required for serializing or deserializing JSON data for
Kotlin classes with Jackson, so make sure to add the
com.fasterxml.jackson.module:jackson-module-kotlin dependency to your project if
you have such need. It is automatically registered when found in the classpath.
8.1.2. Extensions
Kotlin extensions provide the ability to extend existing classes with additional functionality. The
Spring Framework Kotlin APIs use these extensions to add new Kotlin-specific conveniences to
existing Spring APIs.
The Spring Framework KDoc API lists and documents all available Kotlin extensions and DSLs.
Keep in mind that Kotlin extensions need to be imported to be used. This means,
for example, that the GenericApplicationContext.registerBean Kotlin extension is
available only if org.springframework.context.support.registerBean is imported.
That said, similar to static imports, an IDE should automatically suggest the import
in most cases.
For example, Kotlin reified type parameters provide a workaround for JVM generics type erasure,
1398
and the Spring Framework provides some extensions to take advantage of this feature. This allows
for a better Kotlin API RestTemplate, for the new WebClient from Spring WebFlux, and for various
other APIs.
Other libraries, such as Reactor and Spring Data, also provide Kotlin extensions for
their APIs, thus giving a better Kotlin development experience overall.
To retrieve a list of User objects in Java, you would normally write the following:
With Kotlin and the Spring Framework extensions, you can instead write the following:
As in Java, users in Kotlin is strongly typed, but Kotlin’s clever type inference allows for shorter
syntax.
8.1.3. Null-safety
One of Kotlin’s key features is null-safety, which cleanly deals with null values at compile time
rather than bumping into the famous NullPointerException at runtime. This makes applications
safer through nullability declarations and expressing “value or no value” semantics without paying
the cost of wrappers, such as Optional. (Kotlin allows using functional constructs with nullable
values. See this comprehensive guide to Kotlin null-safety.)
Although Java does not let you express null-safety in its type-system, the Spring Framework
provides null-safety of the whole Spring Framework API via tooling-friendly annotations declared
in the org.springframework.lang package. By default, types from Java APIs used in Kotlin are
recognized as platform types, for which null-checks are relaxed. Kotlin support for JSR-305
annotations and Spring nullability annotations provide null-safety for the whole Spring Framework
API to Kotlin developers, with the advantage of dealing with null-related issues at compile time.
Libraries such as Reactor or Spring Data provide null-safe APIs to leverage this
feature.
You can configure JSR-305 checks by adding the -Xjsr305 compiler flag with the following options:
-Xjsr305={strict|warn|ignore}.
For kotlin versions 1.1+, the default behavior is the same as -Xjsr305=warn. The strict value is
required to have Spring Framework API null-safety taken into account in Kotlin types inferred from
Spring API but should be used with the knowledge that Spring API nullability declaration could
evolve even between minor releases and that more checks may be added in the future.
1399
Generic type arguments, varargs, and array elements nullability are not supported
yet, but should be in an upcoming release. See this discussion for up-to-date
information.
The Spring Framework supports various Kotlin constructs, such as instantiating Kotlin classes
through primary constructors, immutable classes data binding, and function optional parameters
with default values.
You can declare configuration classes as top level or nested but not inner, since the later requires a
reference to the outer class.
8.1.5. Annotations
The Spring Framework also takes advantage of Kotlin null-safety to determine if an HTTP
parameter is required without having to explicitly define the required attribute. That means
@RequestParam name: String? is treated as not required and, conversely, @RequestParam name: String
is treated as being required. This feature is also supported on the Spring Messaging @Header
annotation.
In a similar fashion, Spring bean injection with @Autowired, @Bean, or @Inject uses this information
to determine if a bean is required or not.
For example, @Autowired lateinit var thing: Thing implies that a bean of type Thing must be
registered in the application context, while @Autowired lateinit var thing: Thing? does not raise an
error if such a bean does not exist.
Following the same principle, @Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car) implies that a
bean of type Toy must be registered in the application context, while a bean of type Car may or may
not exist. The same behavior applies to autowired constructor parameters.
1400
not require any reflection or CGLIB proxies.
class Foo {}
class Bar {
private final Foo foo;
public Bar(Foo foo) {
this.foo = foo;
}
}
In Kotlin, with reified type parameters and GenericApplicationContext Kotlin extensions, you can
instead write the following:
class Foo
When the class Bar has a single constructor, you can even just specify the bean class, the
constructor parameters will be autowired by type:
In order to allow a more declarative approach and cleaner syntax, Spring Framework provides a
Kotlin bean definition DSL It declares an ApplicationContextInitializer through a clean declarative
API, which lets you deal with profiles and Environment for customizing how beans are registered.
• Type inference usually allows to avoid specifying the type for bean references like
ref("bazBean")
• It is possible to use Kotlin top level functions to declare beans using callable references like
1401
bean(::myRouter) in this example
• The FooBar bean will be registered only if the foobar profile is active
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)
You can then use this beans() function to register beans on the application context, as the following
example shows:
Spring Boot is based on JavaConfig and does not yet provide specific support for
functional bean definition, but you can experimentally use functional bean
definitions through Spring Boot’s ApplicationContextInitializer support. See this
Stack Overflow answer for more details and up-to-date information. See also the
experimental Kofu DSL developed in Spring Fu incubator.
1402
8.1.7. Web
Router DSL
These DSL let you write clean and idiomatic Kotlin code to build a RouterFunction instance as the
following example shows:
@Configuration
class RouterRouterConfiguration {
@Bean
fun mainRouter(userHandler: UserHandler) = router {
accept(TEXT_HTML).nest {
GET("/") { ok().render("index") }
GET("/sse") { ok().render("sse") }
GET("/users", userHandler::findAllView)
}
"/api".nest {
accept(APPLICATION_JSON).nest {
GET("/users", userHandler::findAll)
}
accept(TEXT_EVENT_STREAM).nest {
GET("/users", userHandler::stream)
}
}
resources("/**", ClassPathResource("static/"))
}
}
MockMvc DSL
A Kotlin DSL is provided via MockMvc Kotlin extensions in order to provide a more idiomatic Kotlin
API and to allow better discoverability (no usage of static methods).
1403
val mockMvc: MockMvc = ...
mockMvc.get("/person/{name}", "Lee") {
secure = true
accept = APPLICATION_JSON
headers {
contentLanguage = Locale.FRANCE
}
principal = Principal { "foo" }
}.andExpect {
status { isOk }
content { contentType(APPLICATION_JSON) }
jsonPath("$.name") { value("Lee") }
content { json("""{"someBoolean": false}""", false) }
}.andDo {
print()
}
build.gradle.kts
dependencies {
runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
KotlinScriptConfiguration.kt
1404
@Configuration
class KotlinScriptConfiguration {
@Bean
fun kotlinScriptConfigurer() = ScriptTemplateConfigurer().apply {
engineName = "kotlin"
setScripts("scripts/render.kts")
renderFunction = "render"
isSharedEngine = false
}
@Bean
fun kotlinScriptViewResolver() = ScriptTemplateViewResolver().apply {
setPrefix("templates/")
setSuffix(".kts")
}
}
As of Spring Framework 5.3, Kotlin multiplatform serialization is supported in Spring MVC, Spring
WebFlux and Spring Messaging (RSocket). The builtin support currently targets CBOR, JSON, and
ProtoBuf formats.
To enable it, follow those instructions to add the related dependency and plugin. With Spring MVC
and WebFlux, both Kotlin serialization and Jackson will be configured by default if they are in the
classpath since Kotlin serialization is designed to serialize only Kotlin classes annotated with
@Serializable. With Spring Messaging (RSocket), make sure that neither Jackson, GSON or JSONB
are in the classpath if you want automatic configuration, if Jackson is needed configure
KotlinSerializationJsonMessageConverter manually.
8.1.8. Coroutines
Kotlin Coroutines are Kotlin lightweight threads allowing to write non-blocking code in an
imperative way. On language side, suspending functions provides an abstraction for asynchronous
operations while on library side kotlinx.coroutines provides functions like async { } and types like
Flow.
• Deferred and Flow return values support in Spring MVC and WebFlux annotated @Controller
1405
• Extensions for RSocketRequester
Dependencies
build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-
core:${coroutinesVersion}")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-
reactor:${coroutinesVersion}")
}
For return values, the translation from Reactive to Coroutines APIs is the following:
• fun handler(): Mono<T> becomes suspend fun handler(): T or suspend fun handler(): T?
depending on if the Mono can be empty or not (with the advantage of being more statically typed)
• If laziness is not needed, fun handler(mono: Mono<T>) becomes fun handler(value: T) since a
suspending functions can be invoked to get the value parameter.
Flow is Flux equivalent in Coroutines world, suitable for hot or cold stream, finite or infinite
streams, with the following main differences:
• Flow has only a single suspending collect method and operators are implemented as extensions
• map operator supports asynchronous operation (no need for flatMap) since it takes a suspending
function parameter
1406
Read this blog post about Going Reactive with Spring, Coroutines and Kotlin Flow for more details,
including how to run code concurrently with Coroutines.
Controllers
@RestController
class CoroutinesRestController(client: WebClient, banner: Banner) {
@GetMapping("/suspend")
suspend fun suspendingEndpoint(): Banner {
delay(10)
return banner
}
@GetMapping("/flow")
fun flowEndpoint() = flow {
delay(10)
emit(banner)
delay(10)
emit(banner)
}
@GetMapping("/deferred")
fun deferredEndpoint() = GlobalScope.async {
delay(10)
banner
}
@GetMapping("/sequential")
suspend fun sequential(): List<Banner> {
val banner1 = client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
val banner2 = client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
return listOf(banner1, banner2)
}
@GetMapping("/parallel")
suspend fun parallel(): List<Banner> = coroutineScope {
val deferredBanner1: Deferred<Banner> = async {
1407
client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
}
val deferredBanner2: Deferred<Banner> = async {
client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
}
listOf(deferredBanner1.await(), deferredBanner2.await())
}
@GetMapping("/error")
suspend fun error() {
throw IllegalStateException()
}
@GetMapping("/cancel")
suspend fun cancel() {
throw CancellationException()
}
@Controller
class CoroutinesViewController(banner: Banner) {
@GetMapping("/")
suspend fun render(model: Model): String {
delay(10)
model["banner"] = banner
return "index"
}
}
WebFlux.fn
Here is an example of Coroutines router defined via the coRouter { } DSL and related handlers.
1408
@Configuration
class RouterConfiguration {
@Bean
fun mainRouter(userHandler: UserHandler) = coRouter {
GET("/", userHandler::listView)
GET("/api/user", userHandler::listApi)
}
}
Transactions
Transactions on Coroutines are supported via the programmatic variant of the Reactive transaction
management provided as of Spring Framework 5.2.
1409
import org.springframework.transaction.reactive.executeAndAwait
import org.springframework.transaction.reactive.transactional
This section provides some specific hints and recommendations worth for developing Spring
projects in Kotlin.
Final by Default
By default, all classes in Kotlin are final. The open modifier on a class is the opposite of Java’s final:
It allows others to inherit from this class. This also applies to member functions, in that they need
to be marked as open to be overridden.
While Kotlin’s JVM-friendly design is generally frictionless with Spring, this specific Kotlin feature
can prevent the application from starting, if this fact is not taken into consideration. This is because
1410
Spring beans (such as @Configuration annotated classes which by default need to be extended at
runtime for technical reasons) are normally proxied by CGLIB. The workaround is to add an open
keyword on each class and member function of Spring beans that are proxied by CGLIB, which can
quickly become painful and is against the Kotlin principle of keeping code concise and predictable.
• @Component
• @Async
• @Transactional
• @Cacheable
start.spring.io enables the kotlin-spring plugin by default. So, in practice, you can write your Kotlin
beans without any additional open keyword, as in Java.
You can optionally add the data keyword to make the compiler automatically derive the following
members from all properties declared in the primary constructor:
• copy() function
As the following example shows, this allows for easy changes to individual properties, even if
1411
Person properties are read-only:
Common persistence technologies (such as JPA) require a default constructor, preventing this kind
of design. Fortunately, there is a workaround for this “default constructor hell”, since Kotlin
provides a kotlin-jpa plugin that generates synthetic no-arg constructor for classes annotated with
JPA annotations.
If you need to leverage this kind of mechanism for other persistence technologies, you can
configure the kotlin-noarg plugin.
As of the Kay release train, Spring Data supports Kotlin immutable class instances
and does not require the kotlin-noarg plugin if the module uses Spring Data object
mappings (such as MongoDB, Redis, Cassandra, and others).
Injecting Dependencies
Our recommendation is to try to favor constructor injection with val read-only (and non-nullable
when possible) properties, as the following example shows:
@Component
class YourBean(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
)
If you really need to use field injection, you can use the lateinit var construct, as the following
example shows:
@Component
class YourBean {
@Autowired
lateinit var mongoTemplate: MongoTemplate
@Autowired
lateinit var solrClient: SolrClient
}
1412
Injecting Configuration Properties
Therefore, if you wish to use the @Value annotation in Kotlin, you need to escape the $ character by
writing @Value("\${property}").
If you use Spring Boot, you should probably use @ConfigurationProperties instead
of @Value annotations.
As an alternative, you can customize the property placeholder prefix by declaring the following
configuration beans:
@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
}
You can customize existing code (such as Spring Boot actuators or @LocalServerPort) that uses the
${…} syntax, with configuration beans, as the following example shows:
@Bean
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
setIgnoreUnresolvablePlaceholders(true)
}
@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
Checked Exceptions
Java and Kotlin exception handling are pretty close, with the main difference being that Kotlin
treats all exceptions as unchecked exceptions. However, when using proxied objects (for example
classes or methods annotated with @Transactional), checked exceptions thrown will be wrapped by
default in an UndeclaredThrowableException.
To get the original exception thrown like in Java, methods should be annotated with @Throws to
specify explicitly the checked exceptions thrown (for example @Throws(IOException::class)).
Kotlin annotations are mostly similar to Java annotations, but array attributes (which are
extensively used in Spring) behave differently. As explained in the Kotlin documentation you can
omit the value attribute name, unlike other attributes, and specify it as a vararg parameter.
1413
To understand what that means, consider @RequestMapping (which is one of the most widely used
Spring annotations) as an example. This Java annotation is declared as follows:
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
// ...
}
The typical use case for @RequestMapping is to map a handler method to a specific path and method.
In Java, you can specify a single value for the annotation array attribute, and it is automatically
converted to an array.
An alternative for this specific method attribute (the most common one) is to use a shortcut
annotation, such as @GetMapping, @PostMapping, and others.
If the @RequestMapping method attribute is not specified, all HTTP methods will be
matched, not only the GET method.
Testing
This section addresses testing with the combination of Kotlin and Spring Framework. The
recommended testing framework is JUnit 5 along with Mockk for mocking.
Constructor injection
As described in the dedicated section, JUnit 5 allows constructor injection of beans which is pretty
useful with Kotlin in order to use val instead of lateinit var. You can use
@TestConstructor(autowireMode = AutowireMode.ALL) to enable autowiring for all parameters.
1414
@SpringJUnitConfig(TestConfig::class)
@TestConstructor(autowireMode = AutowireMode.ALL)
class OrderServiceIntegrationTests(val orderService: OrderService,
val customerService: CustomerService) {
PER_CLASS Lifecycle
Kotlin lets you specify meaningful test function names between backticks (`). As of JUnit 5, Kotlin
test classes can use the @TestInstance(TestInstance.Lifecycle.PER_CLASS) annotation to enable
single instantiation of test classes, which allows the use of @BeforeAll and @AfterAll annotations on
non-static methods, which is a good fit for Kotlin.
You can also change the default behavior to PER_CLASS thanks to a junit-platform.properties file
with a junit.jupiter.testinstance.lifecycle.default = per_class property.
The following example demonstrates @BeforeAll and @AfterAll annotations on non-static methods:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class IntegrationTests {
@BeforeAll
fun beforeAll() {
application.start()
}
@Test
fun `Find all users on HTML page`() {
client.get().uri("/users")
.accept(TEXT_HTML)
.retrieve()
.bodyToMono<String>()
.test()
.expectNextMatches { it.contains("Foo") }
.verifyComplete()
}
@AfterAll
fun afterAll() {
application.stop()
}
}
1415
Specification-like Tests
You can create specification-like tests with JUnit 5 and Kotlin. The following example shows how to
do so:
class SpecificationLikeTests {
@Nested
@DisplayName("a calculator")
inner class Calculator {
val calculator = SampleCalculator()
@Test
fun `should return the result of adding the first number to the second number`()
{
val sum = calculator.sum(2, 4)
assertEquals(6, sum)
}
@Test
fun `should return the result of subtracting the second number from the first
number`() {
val subtract = calculator.subtract(4, 2)
assertEquals(2, subtract)
}
}
}
Due to a type inference issue, you must use the Kotlin expectBody extension (such as
.expectBody<String>().isEqualTo("toys")), since it provides a workaround for the Kotlin issue with
the Java API.
The easiest way to learn how to build a Spring application with Kotlin is to follow the dedicated
tutorial.
start.spring.io
The easiest way to start a new Spring Framework project in Kotlin is to create a new Spring Boot 2
project on start.spring.io.
Spring Framework now comes with two different web stacks: Spring MVC and Spring WebFlux.
1416
Spring WebFlux is recommended if you want to create applications that will deal with latency, long-
lived connections, streaming scenarios or if you want to use the web functional Kotlin DSL.
For other use cases, especially if you are using blocking technologies such as JPA, Spring MVC and
its annotation-based programming model is the recommended choice.
8.1.11. Resources
We recommend the following resources for people learning how to build applications with Kotlin
and the Spring Framework:
• Kotlin blog
• Awesome Kotlin
Examples
The following Github projects offer examples that you can learn from and possibly even extend:
• spring-kotlin-fullstack: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of
JavaScript or TypeScript
• spring-kotlin-deepdive: A step-by-step migration guide for Boot 1.0 and Java to Boot 2.0 and
Kotlin
Issues
The following list categorizes the pending issues related to Spring and Kotlin support:
• Spring Framework
• Kotlin
1417
◦ Impossible to pass not all SAM argument as function
The Spring Framework provides a dedicated ApplicationContext that supports a Groovy-based Bean
Definition DSL. For more details, see The Groovy Bean Definition DSL.
Further support for Groovy, including beans written in Groovy, refreshable script beans, and more
is available in Dynamic Language Support.
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.
You can find fully working examples of where this dynamic language support can be immediately
useful in Scenarios.
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).
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:
1418
package org.springframework.scripting;
String getMessage();
}
The following example defines a class that has a dependency on the Messenger interface:
package org.springframework.scripting;
String message
}
1419
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 ApplicationContext
implementation as your IoC container. Using the dynamic-language-backed beans
with a plain BeanFactory implementation is supported, but you have to manage the
plumbing of the Spring internals to do so.
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:
<!-- 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>
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.
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.
This section describes exactly how you define Spring-managed beans in any of the supported
dynamic languages.
1420
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
1. Write the test for the dynamic language source code (naturally).
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 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:groovy/> (Groovy)
• <lang:bsh/> (BeanShell)
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
One of the (and perhaps the single) most compelling value adds of the dynamic language support in
Spring is the “refreshable bean” feature.
1421
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).
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.
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>
</beans>
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.
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.
1422
The following listing shows this sample application:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
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
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
1423
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).
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
</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.)
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:
1424
An approach that cannot work
import org.springframework.scripting.Messenger
GroovyMessenger() {}
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
“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-
1425
dynamic-language-backed bean. Now consider another example (again using an example from the
Spring test suite):
package org.springframework.scripting;
package org.springframework.scripting;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
The resulting output from running the above program is (unsurprisingly) 10. (For more interesting
1426
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.
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:
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:
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:
1427
<!-- 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"/>
BeanShell Beans
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.
1428
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;
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;
}
The following example shows the Spring XML that defines an “instance” of the above “class” (again,
we use these terms very loosely here):
See Scenarios for some scenarios where you might want to use BeanShell-based beans.
8.3.3. 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
1429
language support in Spring.
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.
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
1430
<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.
import org.springframework.validation.Validator
import org.springframework.validation.Errors
import org.springframework.beans.TestBean
This last section contains some additional details related to the dynamic language support.
1431
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:
</beans>
See Bean Scopes in The IoC Container for a full discussion of the scoping support in the Spring
Framework.
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
1432
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:
</beans>
The following links go to further resources about the various dynamic languages referenced in this
chapter:
1433