# 语言支持 ## 1. Kotlin [Kotlin](https://kotlinlang.org)是一种以 JVM(和其他平台)为目标的静态类型语言,它允许编写简洁和优雅的代码,同时使用用 Java 编写的现有库提供非常好的[互操作性](https://kotlinlang.org/docs/reference/java-interop.html)。 Spring 框架为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序,就好像 Spring 框架是一个原生 Kotlin 框架一样。除了 Java 之外,参考文档的大多数代码示例都是在 Kotlin 中提供的。 用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring 引导和它的[dedicated Kotlin support](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-kotlin.html)。[这个全面的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)将教你如何使用[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)用 Kotlin 构建 Spring 引导应用程序。 如果你需要支持,可以随时加入[Kotlin Slack](https://slack.kotlinlang.org/)的 # Spring 通道,或者使用`spring`和`kotlin`作为标记在[StackOverflow](https://stackoverflow.com/questions/tagged/spring+kotlin)上提问。 ### 1.1.所需经费 Spring 框架 支持 Kotlin 1.3+,需要[`kotlin-stdlib`](https://search. Maven.org/artifact/org.JetBrains. Kotlin/ Kotlin-stdlib)(或其变体之一,如[`kotlin-stdlib-jdk8`](https://search. Maven.org/artifact/org.jetBrains. Kotlin/ Kotlin-stdlib-jdk8))和[`kotlin-reflect`(https:///search. Maven.org.[org. Kotlin.[jetBrains. Classpath]][jetBrains.[refrain 如果你在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上引导一个 Kotlin 项目,则默认情况下会提供它们。 | |对于使用 Jackson 序列化或反序列化 Kotlin 类的 JSON 数据,[Jackson Kotlin module](https://github.com/FasterXML/jackson-module-kotlin)是必需的
,因此,如果你有此需要,请确保将`com.fasterxml.jackson.module:jackson-module-kotlin`依赖项添加到你的项目中。
在 Classpath 中找到时,它会自动注册。| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ### 1.2.扩展 Kotlin [extensions](https://kotlinlang.org/docs/reference/extensions.html)提供了扩展具有附加功能的现有类的能力。 Spring 框架 Kotlin API 使用这些扩展来向现有 Spring API 添加新的 Kotlin 特定的便利。 [Spring Framework KDoc API](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/)列表和文档都是可用的 Kotlin 扩展和 DSL。 | |请记住, Kotlin 扩展需要导入才能使用。这意味着,
例如,`GenericApplicationContext.registerBean` Kotlin 扩展
只有当`org.springframework.context.support.registerBean`被导入时才可用。
也就是说,与静态导入类似,IDE 在大多数情况下应该自动建议导入。| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 例如,[Kotlin reified type parameters](https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters)为 JVM[泛型擦除](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)提供了一种变通方法, Spring 框架提供了一些扩展来利用这一特性。这允许为 Kotlin WebFlux 中的新的`WebClient`API`RestTemplate`以及其他各种 API 提供更好的 API。 | |其他库,例如 Reactor 和 Spring Data,也为它们的 API 提供了 Kotlin 扩展,因此总体上提供了更好的 Kotlin 开发体验。| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------| 要在 Java 中检索`User`对象的列表,通常需要编写以下内容: ``` Flux users = client.get().retrieve().bodyToFlux(User.class) ``` 通过 Kotlin 和 Spring 框架扩展,你可以改为编写以下内容: ``` val users = client.get().retrieve().bodyToFlux() // or (both are equivalent) val users : Flux = client.get().retrieve().bodyToFlux() ``` 正如在 Java 中一样, Kotlin 中的`users`是强类型的,但是 Kotlin 聪明的类型推断允许更短的语法。 ### 1.3.零安全 Kotlin 的关键特性之一是[零安全](https://kotlinlang.org/docs/reference/null-safety.html),它在编译时干净地处理`null`值,而不是在运行时遇到著名的`NullPointerException`。这使得应用程序通过可否定性声明和表达“值或无值”语义而更安全,而不需要支付包装器的费用,例如`Optional`。( Kotlin 允许使用具有可空的值的函数结构。参见[comprehensive guide to Kotlin null-safety](https://www.baeldung.com/kotlin-null-safety)。) 尽管 Java 不允许在其类型系统中表示空安全,但 Spring 框架通过在`org.springframework.lang`包中声明的对工具友好的注释提供了[null-safety of the whole Spring Framework API](core.html#null-safety)。默认情况下,来自 Kotlin 中使用的 Java API 的类型被识别为[平台类型](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types),对此可以放松空值检查。[Kotlin support for JSR-305 annotations](https://kotlinlang.org/docs/reference/java-interop.html#jsr-305-support)和 Spring 空值注释为 Kotlin 开发人员提供了整个 Spring Framework API 的空安全性,并具有在编译时处理`null`相关问题的优点。 | |诸如 Reactor 或 Spring Data 之类的库提供了空安全的 API 来利用此功能。| |---|-----------------------------------------------------------------------------------------| 你可以通过添加`-Xjsr305`编译器标志和以下选项来配置 JSR-305 检查:`-Xjsr305={strict|warn|ignore}`。 对于 Kotlin 版本 1.1+,默认行为与`-Xjsr305=warn`相同。在从 Spring API 推断出的 Kotlin 类型中,`strict`值需要将 Spring FrameworkAPI 空安全性考虑在内,但在使用时应了解 Spring API 空性声明即使在较小的版本之间也可以发展,并且将来可能会添加更多的检查。 | |目前还不支持泛型类型参数、varargs 和数组元素的可空性,
,但应该在即将发布的版本中支持。有关最新信息,请参见[这次讨论](https://github.com/Kotlin/KEEP/issues/79)。| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ### 1.4.类和接口 Spring 框架支持各种 Kotlin 构造,例如通过主构造函数实例化 Kotlin 类、不可变类数据绑定和具有默认值的函数可选参数。 Kotlin 参数名称是通过专用的`KotlinReflectionParameterNameDiscoverer`来识别的,其允许查找接口方法参数名称,而不需要在编译过程中启用 Java8`-parameters`编译器标志。 你可以将配置类声明为[顶层或嵌套的,但不是内部的](https://kotlinlang.org/docs/reference/nested-classes.html),因为后者需要对外部类的引用。 ### 1.5.注解 Spring 框架还利用[Kotlin null-safety](https://kotlinlang.org/docs/reference/null-safety.html)来确定是否需要 HTTP 参数,而无需显式地定义`required`属性。这意味着`@RequestParam name: String?`被视为不需要,相反,`@RequestParam name: String`被视为需要。 Spring 消息传递`@Header`注释也支持此功能。 以类似的方式, Spring Bean 带有`@Autowired`、`@Bean`或`@Inject`的注入使用该信息来确定是否需要 Bean。 例如,`@Autowired lateinit var thing: Thing`意味着必须在应用程序上下文中注册类型`Thing`的 Bean,而`@Autowired lateinit var thing: Thing?`如果不存在这样的 Bean,则不会引发错误。 遵循相同的原则,`@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)`意味着类型`Toy`的 Bean 必须在应用程序上下文中注册,而类型`Car`的 Bean 可能存在,也可能不存在。同样的行为也适用于自动连线构造函数参数。 | |如果在具有属性或主构造函数
参数的类上使用 Bean 验证,则可能需要使用[注释使用-站点目标](https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets),
,例如`@field:NotNull`或`@get:Size(min=5, max=15)`,如[这个堆栈溢出响应](https://stackoverflow.com/a/35853200/1092077)中所述。| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ### 1.6. Bean 定义 DSL Spring Framework 支持通过使用 lambdas 作为 XML 或 Java 配置的替代方法(`@Configuration`和`@Bean`)以功能方式注册 bean。简而言之,它允许你用 lambda 注册 bean,lambda 充当`FactoryBean`。这种机制非常有效,因为它不需要任何反射或 CGlib 代理。 例如,在 Java 中,你可以编写以下内容: ``` class Foo {} class Bar { private final Foo foo; public Bar(Foo foo) { this.foo = foo; } } GenericApplicationContext context = new GenericApplicationContext(); context.registerBean(Foo.class); context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class))); ``` 在 Kotlin 中,使用具体化的类型参数和`GenericApplicationContext` Kotlin 扩展,你可以改为编写以下内容: ``` class Foo class Bar(private val foo: Foo) val context = GenericApplicationContext().apply { registerBean() registerBean { Bar(it.getBean()) } } ``` 当类`Bar`只有一个构造函数时,你甚至可以只指定 Bean 类,构造函数参数将根据类型自动连线: ``` val context = GenericApplicationContext().apply { registerBean() registerBean() } ``` 为了允许更多的声明性方法和更干净的语法, Spring Framework 提供了[Kotlin bean definition DSL](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.context.support/-bean-definition-dsl/)它通过一个干净的声明性 API 声明`ApplicationContextInitializer`,它允许你处理配置文件和`Environment`,以自定义如何注册 bean。 在下面的示例中,请注意: * 类型推理通常允许避免为 Bean 引用指定类型,比如`ref("bazBean")` * 在本例中,可以使用 Kotlin 顶级函数使用`bean(::myRouter)`之类的可调用引用来声明 bean。 * 当指定`bean()`或`bean(::myRouter)`时,参数将按类型自动连线。 * 只有在`foobar`配置文件处于活动状态时,才会注册`FooBar` Bean ``` class Foo class Bar(private val foo: Foo) class Baz(var message: String = "") class FooBar(private val baz: Baz) val myBeans = beans { bean() bean() bean("bazBean") { Baz().apply { message = "Hello world" } } profile("foobar") { bean { FooBar(ref("bazBean")) } } bean(::myRouter) } fun myRouter(foo: Foo, bar: Bar, baz: Baz) = router { // ... } ``` | |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean
进行自定义注册逻辑。| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------| 然后,你可以使用这个`beans()`函数在应用程序上下文中注册 bean,如下例所示: ``` val context = GenericApplicationContext().apply { myBeans.initialize(this) refresh() } ``` | |Spring boot 是基于 javaconfig 和[does not yet provide specific support for functional bean definition](https://github.com/spring-projects/spring-boot/issues/8115),
,但可以通过 Spring boot 的`ApplicationContextInitializer`支持实验性地使用函数 Bean 定义。
查看[这个堆栈溢出回答](https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685)以获得更多详细信息和最新信息。另见[Spring Fu incubator](https://github.com/spring-projects/spring-fu)中开发的实验 Kofu DSL。| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ### 1.7.万维网 #### 1.7.1.路由器 DSL Spring Framework 自带的路由器 DSL 有 3 种类型: * WebMVC.FNDSL with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.servlet.function/router.html) * webflux.FN[Reactive](web-reactive.html#webflux-fn)dsl with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/router.html) * webflux.FN[Coroutines](#coroutines)dsl with[科洛特尔{}](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html) 这些 DSL 允许你编写干净且惯用的代码来构建`RouterFunction`实例,如下例所示: ``` @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/")) } } ``` | |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean
进行自定义注册逻辑。当你需要根据动态数据(例如,来自数据库)注册路由时,这可能是有用的
。| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 具体例子见[Mixit 项目](https://github.com/mixitconf/mixit/)。 #### 1.7.2.MockMVC DSL Kotlin DSL 通过 Kotlin 扩展提供,以便提供更惯用的 Kotlin API 并允许更好的可发现性(不使用静态方法)。 ``` 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() } ``` #### 1.7.3. Kotlin 脚本模板 Spring Framework 提供了一个[`ScriptTemplateView`](https://DOCS. Spring.io/ Spring-framework/DOCS/current/javadoc-api/org/springframework/web/ Servlet/view/script/scripttemplateView.html),它支持[JSR-223](https://www.jcp.org/en/jsr/detail?id=223)通过使用脚本引擎来呈现模板。 通过利用`scripting-jsr223`依赖关系,可以使用这样的特性来呈现带有[kotlinx.html](https://github.com/Kotlin/kotlinx.html)DSL 或 Kotlin 多行插值`String`的基于 Kotlin 的模板。 `build.gradle.kts` ``` dependencies { runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}") } ``` 配置通常使用`ScriptTemplateConfigurer`和`ScriptTemplateViewResolver`bean。 `KotlinScriptConfiguration.kt` ``` @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") } } ``` 有关更多详细信息,请参见[kotlin-script-templating](https://github.com/sdeleuze/kotlin-script-templating)示例项目。 #### 1.7.4. Kotlin 多平台序列化 在 Spring Framework5.3 中,[Kotlin multiplatform serialization](https://github.com/Kotlin/kotlinx.serialization)在 Spring MVC、 Spring WebFlux 和 Spring Messaging 中得到了支持。内置支持目前只针对 JSON 格式。 要启用它,请按照[那些指示](https://github.com/Kotlin/kotlinx.serialization#setup)添加相关的依赖项和插件。使用 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都在 Classpath 中,则它们将默认地被配置,因为 Kotlin 序列化被设计为仅序列化用注释的 Kotlin 类。使用 Spring 消息传递,如果你想要自动配置,请确保 Jackson、GSON 或 JSONB 都不在 Classpath 中,如果需要配置`KotlinSerializationJsonMessageConverter`Jackson,请手动配置。 ### 1.8.协理 Kotlin [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)是 Kotlin 轻量级线程,允许以强制方式编写非阻塞代码。在语言端,挂起函数为异步操作提供了一个抽象,而在库端[Kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines)提供了类似[`async { }`](https:// Kotlin.github.io/kotlinx.io/kotlinx-coroutines-core-core/kotlinx.coroutines/core/kotlinx.coroutines/async.html)和[<`Flow`]等类型的函数(https:// Kotlin.gitlinx.io/kotlinx.coroutines/kotlinx.flow/kofindex.html/-coroutines.html)。 Spring 框架在以下范围上为协程提供支持: * [Deferred](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html)和[Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)在 Spring MVC 和 WebFlux 注释`@Controller`中返回支持的值 * 在 Spring MVC 和 WebFlux 中挂起功能支持`@Controller` * WebFlux[client](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.client/index.html)和[server](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/index.html)函数 API 的扩展。 * WebFlux.FN[科洛特尔{}](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL * 挂起函数和`Flow`在 RSocket 中支持`@MessageMapping`注释的方法 * [`RSocketRequester`]的扩展(https://DOCS. Spring.io/ Spring-framework/DOCS/5.3.16/kdoc-api/ Spring-framework/org.springframework.messing.rsocket/index.html) #### 1.8.1.依赖关系 当`kotlinx-coroutines-core`和`kotlinx-coroutines-reactor`依赖项位于 Classpath 中时,将启用协程支持: `build.gradle.kts` ``` dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:${coroutinesVersion}") } ``` 支持`1.4.0`及以上版本。 #### 1.8.2.反应性如何转化为协程? 对于返回值,从 Active 到 CoroutineAPI 的转换如下: * `fun handler(): Mono`变为`suspend fun handler()` * `fun handler(): Mono`变为`suspend fun handler(): T`或`suspend fun handler(): T?`取决于`Mono`是否为空(具有更静态类型的优点) * `fun handler(): Flux`变为`fun handler(): Flow` 输入参数: * 如果不需要惰性,则`fun handler(mono: Mono)`变为`fun handler(value: T)`,因为可以调用挂起的函数来获得值参数。 * 如果需要惰性,则`fun handler(mono: Mono)`变为`fun handler(supplier: suspend () → T)`或`fun handler(supplier: suspend () → T?)` [`Flow`](https:// Kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)在 coroutines 世界中是`Flux`等价的,适用于热流或冷流,有限或无限流,有以下主要区别: * `Flow`是推拉式混合动力,而`Flux`是推拉式混合动力 * 背压是通过悬挂功能实现的。 * `Flow`只有一个[单挂起`collect`方法](https:// Kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html)和运算符实现为[extensions](https://kotlinlang.org/docs/reference/extensions.html) * [运营商很容易实现。](https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/common/src/flow/operators)感谢协程 * 扩展允许将自定义运算符添加到`Flow` * 收集操作是挂起的功能 * [`map`运算符](https:// Kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html)支持异步操作(不需要`flatMap`),因为它需要一个挂起的函数参数 阅读这篇关于[Going Reactive with Spring, Coroutines and Kotlin Flow](https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow)的博客文章,了解更多细节,包括如何与协程同时运行代码。 #### 1.8.3.控制器 下面是一个协程`@RestController`的例子。 ``` @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 { val banner1 = client .get() .uri("/suspend") .accept(MediaType.APPLICATION_JSON) .awaitExchange() .awaitBody() val banner2 = client .get() .uri("/suspend") .accept(MediaType.APPLICATION_JSON) .awaitExchange() .awaitBody() return listOf(banner1, banner2) } @GetMapping("/parallel") suspend fun parallel(): List = coroutineScope { val deferredBanner1: Deferred = async { client .get() .uri("/suspend") .accept(MediaType.APPLICATION_JSON) .awaitExchange() .awaitBody() } val deferredBanner2: Deferred = async { client .get() .uri("/suspend") .accept(MediaType.APPLICATION_JSON) .awaitExchange() .awaitBody() } listOf(deferredBanner1.await(), deferredBanner2.await()) } @GetMapping("/error") suspend fun error() { throw IllegalStateException() } @GetMapping("/cancel") suspend fun cancel() { throw CancellationException() } } ``` 还支持`@Controller`的视图呈现。 ``` @Controller class CoroutinesViewController(banner: Banner) { @GetMapping("/") suspend fun render(model: Model): String { delay(10) model["banner"] = banner return "index" } } ``` #### 1.8.4.WebFlux.FN 下面是通过[科洛特尔{}](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL 和相关处理程序定义的协程路由器的示例。 ``` @Configuration class RouterConfiguration { @Bean fun mainRouter(userHandler: UserHandler) = coRouter { GET("/", userHandler::listView) GET("/api/user", userHandler::listApi) } } ``` ``` class UserHandler(builder: WebClient.Builder) { private val client = builder.baseUrl("...").build() suspend fun listView(request: ServerRequest): ServerResponse = ServerResponse.ok().renderAndAwait("users", mapOf("users" to client.get().uri("...").awaitExchange().awaitBody())) suspend fun listApi(request: ServerRequest): ServerResponse = ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait( client.get().uri("...").awaitExchange().awaitBody()) } ``` #### 1.8.5.交易 协程上的事务通过 Spring 框架 5.2 提供的反应式事务管理的编程变体来支持。 对于挂起的函数,提供了`TransactionalOperator.executeAndAwait`扩展。 ``` import org.springframework.transaction.reactive.executeAndAwait class PersonRepository(private val operator: TransactionalOperator) { suspend fun initDatabase() = operator.executeAndAwait { insertPerson1() insertPerson2() } private suspend fun insertPerson1() { // INSERT SQL statement } private suspend fun insertPerson2() { // INSERT SQL statement } } ``` 对于 Kotlin `Flow`,提供了一个`Flow.transactional`扩展。 ``` import org.springframework.transaction.reactive.transactional class PersonRepository(private val operator: TransactionalOperator) { fun updatePeople() = findPeople().map(::updatePerson).transactional(operator) private fun findPeople(): Flow { // SELECT SQL statement } private suspend fun updatePerson(person: Person): Person { // UPDATE SQL statement } } ``` ### 1.9. Spring Kotlin 个项目 本节提供了一些值得在 Kotlin 中开发 Spring 项目的具体提示和建议。 #### 1.9.1.默认情况下为 final 默认情况下,[ Kotlin 中的所有类都是`final`](https://discussion.kotlinlang.org/t/classes-final-by-default/166)。类上的`open`修饰符与 Java 的`final`相反:它允许其他人继承这个类。这也适用于成员函数,因为它们需要标记为`open`才能被重写。 虽然 Kotlin 的 JVM 友好设计通常与 Spring 无摩擦,但如果不考虑这一事实,则此特定的 Kotlin 特性可以阻止应用程序启动。这是因为 Spring bean(例如`@Configuration`注释类,由于技术原因,默认情况下需要在运行时进行扩展)通常是由 CGLIB 代理的。解决方法是在 Spring bean 的每个类和成员函数上添加一个`open`关键字,这些 bean 由 CGlib 代理,这可能很快就会变得很痛苦,并且违反 Kotlin 保持代码简洁和可预测的原则。 | |也可以通过使用`@Configuration(proxyBeanMethods = false)`.
来避免配置类的 CGLIB 代理,参见[`proxyBeanMethods`Javadoc](https://DOCS. Spring.io/ Spring-framework/DOCS/5.3.16/javadoc-api/org/springframework/context/annotation/configuration.html#proxybeanMethods---)了解更多详细信息。| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 幸运的是, Kotlin 提供了一个[`kotlin-spring`](https://kotlinlang.org/DOCS/reference/compiler-plugins.html# Kotlin- Spring-compiler-plugin)插件(`kotlin-allopen`插件的预配置版本),该插件自动打开带有以下注释或元注释的类型的类及其成员函数: * `@Component` * `@Async` * `@Transactional` * `@Cacheable` 元注释支持意味着使用`@Configuration`、`@Controller`、`@RestController`、`@Service`或`@Repository`进行注释的类型会自动打开,因为这些注释是用`@Component`进行元注释的。 [start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)默认情况下启用`kotlin-spring`插件。因此,在实践中,你可以在不添加任何`open`关键字的情况下编写 Kotlin bean,就像在 Java 中一样。 | |Spring 框架文档中的 Kotlin 代码示例没有在类及其成员函数上显式地指定`open`。这些示例是使用`kotlin-allopen`插件为
项目编写的,因为这是最常用的设置。| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| #### 1.9.2.使用不可变类实例实现持久性 在 Kotlin 中,在主构造函数中声明只读属性是很方便的,并且被认为是一种最佳实践,如下例所示: ``` class Person(val name: String, val age: Int) ``` 你可以选择添加[the`data`关键字](https://kotlinlang.org/DOCS/reference/data-classes.html),使编译器自动从主构造函数中声明的所有属性派生出以下成员: * `equals()`和`hashCode()` * `toString()`的形式`"User(name=John, age=42)"` * `componentN()`与其声明顺序中的属性对应的函数 * `copy()`函数 正如下面的示例所示,这允许对单个属性进行简单的更改,即使`Person`属性是只读的: ``` data class Person(val name: String, val age: Int) val jack = Person(name = "Jack", age = 1) val olderJack = jack.copy(age = 2) ``` 常见的持久性技术(例如 JPA)需要一个默认的构造函数,从而阻止了这种设计。幸运的是,这个[“默认构造函数地狱”](https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell)有一个解决方法,因为 Kotlin 提供了一个[`kotlin-jpa`](https://kotlinlang.org/DOCS/reference/compiler-plugins.html# Kotlin- JPA-compiler-plugin)插件,它为带有 JPA 注释的类生成合成的无参数构造函数。 如果需要为其他持久性技术利用这种机制,可以配置[`kotlin-noarg`](https://kotlinlang.org/DOCS/reference/compiler-plugins.html#how-to-use-no-arg-plugin)插件。 | |在 Kay Release Train 中, Spring 数据支持 Kotlin 不可变类实例,并且如果模块使用 Spring 数据对象映射`kotlin-noarg`(例如 MongoDB、Redis、Cassandra 和其他),则`kotlin-noarg`不需要这就是为什么在上面的`@Autowired constructor`示例中不需要显式的`@Autowired constructor`的原因。| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 如果确实需要使用字段注入,可以使用`lateinit var`构造,如下例所示: ``` @Component class YourBean { @Autowired lateinit var mongoTemplate: MongoTemplate @Autowired lateinit var solrClient: SolrClient } ``` #### 1.9.4.注入配置属性 在 Java 中,你可以通过使用注释(例如`@Value("${property}")`)注入配置属性。然而,在 Kotlin 中,`$`是用于[字符串插值](https://kotlinlang.org/docs/reference/idioms.html#string-interpolation)的保留字符。 因此,如果希望在 Kotlin 中使用`@Value`注释,则需要通过写`@Value("\${property}")`来转义`$`字符。 | |如果使用 Spring boot,则可能应该使用[`@ConfigurationProperties`](https://DOCS. Spring.io/ Spring-boot/DOCS/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties)代替`@Value`注释。| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 作为一种选择,你可以通过声明以下配置 bean 来定制属性占位符前缀: ``` @Bean fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply { setPlaceholderPrefix("%{") } ``` 你可以使用配置 bean 自定义使用`${…​}`语法的现有代码(例如 Spring 引导执行器或`@LocalServerPort`),如下例所示: ``` @Bean fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply { setPlaceholderPrefix("%{") setIgnoreUnresolvablePlaceholders(true) } @Bean fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer() ``` #### 1.9.5.已检查的异常 Java 和[Kotlin exception handling](https://kotlinlang.org/docs/reference/exceptions.html)非常接近,主要区别在于 Kotlin 将所有异常都视为未经检查的异常。但是,当使用代理对象(例如,用`@Transactional`注释的类或方法)时,抛出的选中异常将默认包装在`UndeclaredThrowableException`中。 要像在 Java 中一样获得原始抛出的异常,应该使用[`@Throws`](https://kotlinlang.org/api/latest/jvm/stdlib/ Kotlin.jvm/-throws/index.html)对方法进行注释,以显式指定抛出的检查过的异常(例如`@Throws(IOException::class)`)。 #### 1.9.6.注释数组属性 Kotlin 注释大多类似于 Java 注释,但是数组属性(在 Spring 中广泛使用)的行为是不同的。正如在[Kotlin documentation](https://kotlinlang.org/docs/reference/annotations.html)中所解释的,与其他属性不同,你可以省略`value`属性名称,并将其指定为`vararg`参数。 要理解这意味着什么,可以将`@RequestMapping`(这是使用最广泛的 Spring 注释之一)作为示例。此 Java 注释声明如下: ``` public @interface RequestMapping { @AliasFor("path") String[] value() default {}; @AliasFor("value") String[] path() default {}; RequestMethod[] method() default {}; // ... } ``` `@RequestMapping`的典型用例是将处理程序方法映射到特定的路径和方法。在 Java 中,你可以为 Annotation Array 属性指定一个值,然后将其自动转换为一个数组。 这就是为什么可以写`@RequestMapping(value = "/toys", method = RequestMethod.GET)`或`@RequestMapping(path = "/toys", method = RequestMethod.GET)`。 但是,在 Kotlin 中,你必须写`@RequestMapping("/toys", method = [RequestMethod.GET])`或`@RequestMapping(path = ["/toys"], method = [RequestMethod.GET])`(需要用命名的数组属性指定方括号)。 对于这个特定的`method`属性(最常见的一种),另一种选择是使用快捷方式注释,例如`@GetMapping`,`@PostMapping`等。 | |如果`@RequestMapping``method`属性未指定,则所有 HTTP 方法都将
进行匹配,而不仅仅是`GET`方法。| |---|------------------------------------------------------------------------------------------------------------------------------| #### 1.9.7.测试 本节讨论使用 Kotlin 和 Spring 框架的组合进行的测试。推荐的测试框架是[JUnit 5](https://junit.org/junit5/)以及用于模拟的[Mockk](https://mockk.io/)。 | |如果你正在使用 Spring 引导,请参见[这个相关的文档](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-kotlin-testing)。| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------| ##### 构造函数注入 正如在[专用部分](testing.html#testcontext-junit-jupiter-di#spring-web-reactive)中所描述的,JUnit5 允许构造函数注入对 Kotlin 非常有用的 bean,以便使用`val`而不是`lateinit var`。可以使用[`@TestConstructor(autowireMode = AutowireMode.ALL)`](https://DOCS. Spring.io/ Spring-framework/DOCS/5.3.16/javadoc-api/org/springframework/test/context/testconstructor.html)为所有参数启用自动布线。 ``` @SpringJUnitConfig(TestConfig::class) @TestConstructor(autowireMode = AutowireMode.ALL) class OrderServiceIntegrationTests(val orderService: OrderService, val customerService: CustomerService) { // tests that use the injected OrderService and CustomerService } ``` ##### `PER_CLASS`生命周期 Kotlin 让你在 backticks(```). As of JUnit 5, Kotlin test classes can use the `@TestInstance() .test() .expectNextMatches { it.contains("Foo") } .verifyComplete() } @AfterAll fun afterAll() { application.stop() } } ``` ##### 类似规范的测试 你可以使用 JUnit5 和 Kotlin 创建类似于规范的测试。下面的示例展示了如何做到这一点: ``` 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) } } } ``` ##### `WebTestClient` Kotlin 中的类型推断问题 由于[类型推断问题](https://youtrack.jetbrains.com/issue/KT-5464),你必须使用 Kotlin `expectBody`扩展(例如`.expectBody().isEqualTo("toys")`),因为它为 Java API 的 Kotlin 问题提供了解决方法。 另见相关的[SPR-16057](https://jira.spring.io/browse/SPR-16057)问题。 ### 1.10.开始 学习如何使用 Kotlin 构建 Spring 应用程序的最简单的方法是遵循[专门的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)。 #### 1.10.1.`start.spring.io` 在 Kotlin 中启动一个新的 Spring 框架项目的最简单的方法是在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上创建一个新的 Spring Boot2 项目。 #### 1.10.2.选择网络口味 Spring Framework 现在带有两个不同的 Web 堆栈:[Spring MVC](web.html#mvc)和[Spring WebFlux](web-reactive.html#spring-web-reactive)。 Spring 如果你希望创建将处理延迟、长寿命连接、流场景的应用程序,或者如果你希望使用具有 Web 功能的 DSL,则推荐使用 WebFlux Kotlin。 对于其他用例,特别是如果你正在使用阻塞技术,例如 JPA, Spring MVC 及其基于注释的编程模型是推荐的选择。 ### 1.11.资源 我们向学习如何使用 Kotlin 和 Spring 框架构建应用程序的人们推荐以下资源: * [Kotlin language reference](https://kotlinlang.org/docs/reference/) * [Kotlin Slack](https://slack.kotlinlang.org/)(带专用 # Spring 频道) * [StackOverflow,with`spring`and`kotlin`tags](https://stackoverflow.com/questions/tagged/ Spring + Kotlin) * [Try Kotlin in your browser](https://play.kotlinlang.org/) * [Kotlin blog](https://blog.jetbrains.com/kotlin/) * [Awesome Kotlin](https://kotlin.link/) #### 1.11.1.例子 以下 GitHub 项目提供了你可以学习甚至扩展的示例: * [spring-boot-kotlin-demo](https://github.com/sdeleuze/spring-boot-kotlin-demo):常规 Spring 引导和 Spring 数据 JPA 项目 * [mixit](https://github.com/mixitconf/mixit): Spring Boot2、WebFlux 和 Reactive Spring Data MongoDB * [spring-kotlin-functional](https://github.com/sdeleuze/spring-kotlin-functional):独立的 WebFlux 和 Functional Bean 定义 DSL * [spring-kotlin-fullstack](https://github.com/sdeleuze/spring-kotlin-fullstack):使用 Kotlin2js 代替 JavaScript 或 TypeScript 的 fullstack 示例 * [spring-petclinic-kotlin](https://github.com/spring-petclinic/spring-petclinic-kotlin): Spring PetClinic 样本应用程序的 Kotlin 版本 * [spring-kotlin-deepdive](https://github.com/sdeleuze/spring-kotlin-deepdive):引导 1.0 和 Java 到引导 2.0 和 Kotlin 的逐步迁移指南 * [spring-cloud-gcp-kotlin-app-sample](https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-kotlin-samples/spring-cloud-gcp-kotlin-app-sample): Spring 启动与谷歌云平台集成 #### 1.11.2.问题 以下清单对与 Spring 和 Kotlin 支持有关的未决问题进行了分类: * Spring Framework * [Unable to use WebTestClient with mock server in Kotlin](https://github.com/spring-projects/spring-framework/issues/20606) * [在泛型、变量和数组元素级别支持零安全](https://github.com/spring-projects/spring-framework/issues/20496) * Kotlin * [Parent issue for Spring Framework support](https://youtrack.jetbrains.com/issue/KT-6380) * [Kotlin requires type inference where Java doesn’t](https://youtrack.jetbrains.com/issue/KT-5464) * [具有开放类的智能强制回归](https://youtrack.jetbrains.com/issue/KT-20283) * [不可能传递不是所有的 SAM 参数作为函数](https://youtrack.jetbrains.com/issue/KT-14984) * [通过脚本变量直接支持 JSR223 绑定](https://youtrack.jetbrains.com/issue/KT-15125) * [Kotlin properties do not override Java-style getters and setters](https://youtrack.jetbrains.com/issue/KT-6653) ## 2. Apache Groovy Groovy 是一种功能强大的、可选类型的动态语言,具有静态类型和静态编译功能。它提供了简洁的语法,并与任何现有的 Java 应用程序平滑地集成在一起。 Spring 框架提供了一个专用的`ApplicationContext`,该框架支持基于 Groovy 的 Bean 定义 DSL。有关更多详细信息,请参见[The Groovy Bean Definition DSL](core.html#groovy-bean-definition-dsl)。 对 Groovy 的进一步支持,包括用 Groovy 编写的 bean、可刷新的脚本 bean,以及[动态语言支持](#dynamic-language)中提供的更多支持。 ## 3. 动态语言支持 Spring 为使用已经通过使用动态语言(例如 Groovy)定义的类和对象提供了全面的支持。这种支持使你可以在受支持的动态语言中编写任意数量的类,并让 Spring 容器透明地实例化、配置和依赖注入结果对象。 Spring 的脚本支持主要针对 Groovy 和 BeanShell。除了那些特别支持的语言之外,JSR-223 脚本机制还支持与任何具有 JSR-223 功能的语言提供程序的集成(从 Spring 4.2 开始),例如 JRuby。 你可以在[Scenarios](#dynamic-language-scenarios)中找到充分工作的示例,说明这种动态语言支持可以立即发挥作用。 ### 3.1.第一个例子 本章的主要内容是详细描述动态语言支持。在深入研究动态语言支持的所有细节和细节之前,我们先看一个在动态语言中定义的 Bean 的快速示例。这第一个 Bean 的动态语言是 Groovy。(这个示例的基础取自 Spring 测试套件。如果你想在任何其他受支持的语言中看到等效的示例,请查看源代码)。 下一个示例显示了 Groovy Bean 将要实现的`Messenger`接口。请注意,这个接口是用纯 Java 定义的。通过引用`Messenger`注入的依赖对象不知道底层实现是 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... } } ``` 下面的示例在 Groovy 中实现了`Messenger`接口: ``` // from the file 'Messenger.groovy' package org.springframework.scripting.groovy; // import the Messenger interface (written in Java) that is to be implemented import org.springframework.scripting.Messenger // define the implementation in Groovy class GroovyMessenger implements Messenger { String message } ``` | |要使用自定义的动态语言标记来定义动态语言支持的 bean,你
需要在 Spring XML 配置文件的顶部具有 XML 模式序言。
还需要使用 Spring `ApplicationContext`实现作为你的 IOC
容器。支持使用带有普通`BeanFactory`实现的动态语言支持的 bean,但是你必须管理 Spring 内部
的管道才能这样做。

有关基于模式的配置的更多信息,请参见[基于 XML 模式的配置](#xsd-schemas-lang)。| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 最后,下面的示例展示了 Bean 定义,这些定义会将 Groovy 定义的实现注入到类的实例中: ``` ``` `bookingService` Bean(a`DefaultBookingService`)现在可以正常使用其私有`messenger`成员变量,因为注入到它的`Messenger`实例是`Messenger`实例。这里没有什么特别的——只有普通的 Java 和普通的 Groovy。 希望前面的 XML 片段是不言自明的,但如果不是,也不要过分担心。继续阅读关于前面配置的原因和原因的深入细节。 ### 3.2.定义由动态语言支持的 bean 本节详细描述了如何在任何受支持的动态语言中定义 Spring-managed bean。 请注意,本章并不试图解释所支持的动态语言的语法和习语。例如,如果你想使用 Groovy 在应用程序中编写某些类,我们假设你已经了解 Groovy。如果你需要更多关于动态语言本身的详细信息,请参阅本章末尾的[更多资源](#dynamic-language-resources)。 #### 3.2.1.共同概念 使用动态语言支持的 bean 所涉及的步骤如下: 1. 为动态语言编写测试源代码(当然). 2. 然后编写动态语言的源代码本身. 3. 通过在 XML 配置中使用适当的``元素来定义你的动态语言支持的 bean(你可以通过使用 Spring API 以编程方式定义这样的 bean,尽管你将不得不查询源代码以了解如何做到这一点,因为本章不涉及这种类型的高级配置)。请注意,这是一个迭代步骤。对于每个动态语言源文件,至少需要一个 Bean 定义(尽管多个 Bean 定义可以引用相同的源文件)。 前两个步骤(测试和编写动态语言源文件)超出了本章的范围。请参阅你所选择的动态语言的语言规范和参考手册,并继续开发你的动态语言源文件。不过,你首先想阅读本章的其余部分,因为 Spring 的动态语言支持确实对动态语言源文件的内容进行了一些(小)假设。 ##### \元素 在[前一节](#dynamic-language-beans-concepts)列表中的最后一步涉及定义动态语言支持的 Bean 定义,对于你想要配置的每个 Bean 定义一个定义(这与普通的 JavaBean 配置没有什么不同)。但是,你可以使用``元素来定义支持动态语言的 Bean,而不是指定要由容器实例化和配置的类的完全限定类名称。 每个受支持的语言都有一个对应的``元素: * `` * `` * ``(JSR-223,例如使用 JRuby) 可用于配置的确切属性和子元素取决于 Bean 所定义的语言(本章后面的语言相关章节详细介绍了这一点)。 ##### 可刷新的咖啡豆 Spring 中动态语言支持的最引人注目的增值之一(或许也是唯一的)是“可刷新 Bean”特性。 可刷新的 Bean 是动态语言支持的 Bean。 Bean 通过少量配置,支持动态语言的动态文件可以监视其底层源文件资源中的更改,然后在动态语言源文件更改时重新加载自身(例如,当你编辑和保存对文件系统上的文件的更改时)。 这使你能够将任意数量的动态语言源文件部署为应用程序的一部分,配置 Spring 容器以创建由动态语言源文件支持的 bean(使用本章中描述的机制),以及(稍后, Bean 随着需求的变化或其他一些外部因素起作用),编辑动态语言源文件,并将它们所做的任何变化反映在由所更改的动态语言源文件支持的 Bean 中。没有必要关闭正在运行的应用程序(或者在 Web 应用程序的情况下重新部署)。 Bean 如此修正的动态语言支持从更改的动态语言源文件中获取新的状态和逻辑。 | |默认情况下,此功能是关闭的。| |---|-------------------------------| 现在,我们可以看看一个示例,看看开始使用可刷新 bean 有多容易。要打开可刷新的 bean 特性,你必须在 Bean 定义中的``元素上精确地指定一个附加属性。因此,如果我们坚持使用本章前面的[这个例子](#dynamic-language-a-first-example),下面的示例展示了我们将在 Spring XML 配置中进行哪些更改以实现可刷新的 bean: ``` script-source="classpath:Messenger.groovy"> ``` 这真的是你所要做的一切。在`messenger` Bean 定义上定义的`refresh-check-delay`属性是在对底层动态语言源文件进行任何更改后刷新 Bean 的毫秒数。你可以通过为`refresh-check-delay`属性分配一个负值来关闭刷新行为。请记住,默认情况下,刷新行为是禁用的。如果不想要刷新行为,请不要定义属性。 如果我们接着运行下面的应用程序,我们就可以使用这个可刷新的特性。(请原谅下一段代码中的“跳过环到暂停执行”的恶作剧。)`System.in.read()`调用仅存在于此,以便当你(此场景中的开发人员)关闭并编辑底层动态语言源文件时,程序的执行暂停当程序恢复执行时,在动态语言支持的 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()); } } ``` 然后,为了本例的目的,假设对`Messenger`的`getMessage()`方法的所有调用都必须进行更改,以便消息被引号包围。下面的清单显示了在暂停执行程序时,你(开发人员)应该对`Messenger.groovy`源文件进行的更改: ``` 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 } } ``` 当程序运行时,输入暂停前的输出将是`I Can Do The Frug`。在对源文件进行更改并将其保存并且程序恢复执行之后,在支持动态语言的`Messenger`实现上调用`getMessage()`方法的结果是`'I Can Do The Frug'`(请注意,其中包含了额外的引号)。 如果对脚本的更改发生在`refresh-check-delay`值的窗口内,则不会触发刷新。 Bean 在调用支持动态语言的方法之前,实际上不会接收到对脚本的更改。只有当在支持动态语言的 Bean 上调用方法时,它才会检查其底层脚本源是否已更改。与刷新脚本有关的任何异常(例如遇到编译错误或发现脚本文件已被删除)都会导致将致命异常传播到调用代码中。 Bean 前面描述的可刷新行为不适用于使用``元素表示法定义的动态语言源文件(参见[内联动态语言源文件](#dynamic-language-beans-inline))。此外,它仅适用于实际可以检测到对基础源文件的更改的 bean(例如,通过检查文件系统上存在的动态语言源文件的最后修改日期的代码)。 ##### 内联动态语言源文件 动态语言支持还可以迎合直接嵌入在 Spring Bean 定义中的动态语言源文件。更具体地说,``元素允许你在 Spring 配置文件中立即定义动态语言源。一个示例可能会说明内联脚本功能是如何工作的: ``` package org.springframework.scripting.groovy; import org.springframework.scripting.Messenger class GroovyMessenger implements Messenger { String message } ``` 如果我们不去考虑在 Spring 配置文件中定义动态语言源是否是一种好的实践,``元素在某些场景中可能是有用的。例如,我们可能希望快速地将 Spring `Validator`实现添加到 Spring MVC`Controller`中。这只是一个时刻的工作,使用内联资源。(关于这样的例子,请参见[脚本验证器](#dynamic-language-scenarios-validators)。 ##### 在支持动态语言的 bean 上下文中理解构造函数注入 关于 Spring 的动态语言支持,有一件非常重要的事情需要注意。也就是说,你不能(当前)向支持动态语言的 bean 提供构造函数参数(因此,对于支持动态语言的 bean,构造函数注入是不可用的)。为了使构造函数和属性的这种特殊处理 100% 清晰,以下代码和配置的混合不起作用: 一种行不通的方法 ``` // from the file 'Messenger.groovy' package org.springframework.scripting.groovy; import org.springframework.scripting.Messenger class GroovyMessenger implements Messenger { GroovyMessenger() {} // this constructor is not available for Constructor Injection GroovyMessenger(String message) { this.message = message; } String message String anotherMessage } ``` ``` ``` 在实践中,这种限制并不像最初出现的那样重要,因为 Setter 注入是绝大多数开发人员所青睐的注入风格(关于这是否是一件好事的讨论,我们将留待以后讨论)。 #### 3.2.2.groovy beans 本节描述如何使用 Spring 中在 Groovy 中定义的 bean。 Groovy 主页包括以下描述: Groovy 是一种面向 Java2 平台的敏捷动态语言,它具有许多人们非常喜欢的 Python、Ruby 和 Smalltalk 等语言的特性,使 Java 开发人员可以使用类似 Java 的语法来使用这些特性。” 如果你直接从顶部阅读了这一章,那么你已经获得了支持 Groovy-Dynamic-Language 的[看过一个例子](#dynamic-language-a-first-example) Bean。现在考虑另一个示例(再次使用 Spring 测试套件中的示例): ``` package org.springframework.scripting; public interface Calculator { int add(int x, int y); } ``` 下面的示例在 Groovy 中实现了`Calculator`接口: ``` // from the file 'calculator.groovy' package org.springframework.scripting.groovy class GroovyCalculator implements Calculator { int add(int x, int y) { x + y } } ``` Bean 以下定义使用了在 Groovy 中定义的计算器: ``` ``` 最后,下面的小应用程序执行前面的配置: ``` 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)); } } ``` 运行上述程序的结果输出是(不出所料)`10`。(有关更多有趣的示例,请参见 Dynamic Language Showcase 项目,以获得更复杂的示例,或者参见本章后面的示例[Scenarios](#dynamic-language-scenarios))。 每个 Groovy 源文件不能定义多个类。虽然这在 Groovy 中完全合法,但(可以说)这是一种糟糕的做法。为了采用一致的方法,你应该(在 Spring 团队的意见中)尊重每个源文件一个(公共)类的标准 Java 约定。 ##### 通过使用回调自定义 Groovy 对象 Bean `GroovyObjectCustomizer`接口是一个回调,它允许你将额外的创建逻辑连接到创建支持 Groovy 的过程中。例如,这个接口的实现可以调用任何必需的初始化方法,设置一些默认的属性值,或者指定一个自定义的`MetaClass`。下面的清单显示了`GroovyObjectCustomizer`接口定义: ``` public interface GroovyObjectCustomizer { void customize(GroovyObject goo); } ``` Spring 框架实例化支持 Groovy 的 Bean 的实例,然后将创建的`GroovyObject`传递给指定的`GroovyObjectCustomizer`(如果已经定义了一个)。你可以使用提供的`GroovyObject`引用执行任何你喜欢的操作。我们预计大多数人都希望通过这个回调设置一个自定义`MetaClass`,下面的示例展示了如何这样做: ``` 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`是很容易的,如下例所示: ``` ``` 如果不使用 Spring 名称空间支持,则仍然可以使用`GroovyObjectCustomizer`功能,如下例所示: ``` ``` | |你还可以在 Spring 的`CompilationCustomizer`的相同位置指定一个 Groovy`ImportCustomizer`(例如
)`CompilerConfiguration`对象,甚至可以指定一个完整的 Groovy`CompilerConfiguration`对象。此外,你可以在`ConfigurableApplicationContext.setClassLoader`级别上为你的 bean 设置一个带有自定义
配置的通用`GroovyClassLoader`。这也会导致共享`GroovyClassLoader`的使用,因此在
大量脚本 bean 的情况下是值得推荐的(避免每个 Bean 使用一个孤立的`GroovyClassLoader`实例)。| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| #### 3.2.3.豆壳豆 这一部分描述了如何在 Spring 中使用豆壳豆。 [Beanshell 主页](https://beanshell.github.io/intro.html)包括以下描述: ``` 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. ``` Bean 与 Groovy 相反,支持 BeanShell 的定义需要一些(小的)附加配置。 Spring 中的 BeanShell 动态语言支持的实现是有趣的,因为 Spring 创建了一个 JDK 动态代理,该代理实现了在`script-interfaces`元素的属性值``中指定的所有接口(这就是为什么必须在该属性的值中至少提供一个接口,因此,当你使用 beanshell 支持的 bean 时,将程序转换为接口)。这意味着对 BeanShell 支持的对象的每个方法调用都要通过 JDK 动态代理调用机制。 现在,我们可以展示一个使用基于 BeanShell 的 Bean 的完全工作的示例,该示例实现了本章前面定义的`Messenger`接口。我们再次展示`Messenger`接口的定义: ``` package org.springframework.scripting; public interface Messenger { String getMessage(); } ``` 下面的示例展示了`Messenger`接口的 BeanShell“实现”(我们在这里粗略地使用术语): ``` String message; String getMessage() { return message; } void setMessage(String aMessage) { message = aMessage; } ``` 下面的示例展示了 Spring XML,它定义了上述“类”的一个“实例”(同样,我们在这里非常松散地使用这些术语): ``` ``` 有关可能需要使用基于 BeanShell 的 bean 的一些场景,请参见[Scenarios](#dynamic-language-scenarios)。 ### 3.3.场景 在脚本语言中定义 Spring 托管 bean 将是有益的,这种可能的场景有很多种。本节描述了 Spring 中动态语言支持的两个可能的用例。 #### 3.3.1.脚本 Spring MVC 控制器 可以从使用动态语言支持的 bean 中受益的一组类是 Spring MVC 控制器。在纯 Spring MVC 应用程序中,在很大程度上,通过 Web 应用程序的导航流是由封装在 Spring MVC 控制器中的代码决定的。由于 Web 应用程序的导航流和其他表示层逻辑需要更新,以响应支持问题或更改的业务需求,通过编辑一个或多个动态语言源文件并看到这些更改立即反映在正在运行的应用程序的状态中,很可能更容易实现任何此类所需的更改。 请记住,在 Spring 这样的项目所支持的轻量级架构模型中,你通常的目标是拥有一个非常薄的表示层,应用程序的所有重要业务逻辑都包含在域和服务层类中。 Spring 将 MVC 控制器开发为动态语言支持的 bean,可以通过编辑和保存文本文件来更改表示层逻辑。对这种动态语言源文件的任何更改(取决于配置)都会自动反映在由动态语言源文件支持的 bean 中。 | |要实现对动态语言支持的
bean 的任何更改的自动“拾取”,你必须启用“可刷新 bean”功能。有关此功能的完整处理,请参见[可刷新的咖啡豆](#dynamic-language-refreshable-beans)。| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 下面的示例显示了使用 Groovy 动态语言实现的`org.springframework.web.servlet.mvc.Controller`: ``` // from the file '/WEB-INF/groovy/FortuneController.groovy' 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 javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class FortuneController implements Controller { @Property FortuneService fortuneService ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse httpServletResponse) { return new ModelAndView("tell", "fortune", this.fortuneService.tellFortune()) } } ``` ``` ``` #### 3.3.2.脚本验证器 Spring 应用程序开发的另一个领域是验证,它可能受益于动态语言支持的 bean 所提供的灵活性。相对于正则 Java,使用松散类型的动态语言(也可能支持内联正则表达式)可以更容易地表示复杂的验证逻辑。 同样,将验证器开发为支持动态语言的 bean,可以通过编辑和保存一个简单的文本文件来更改验证逻辑。任何此类更改(取决于配置)都会自动反映在正在运行的应用程序的执行中,并且不需要重新启动应用程序。 | |要实现对动态语言支持的
bean 的任何更改的自动“拾取”,你必须启用“可刷新 bean”功能。有关此功能的完整和详细处理,请参见[可刷新的咖啡豆](#dynamic-language-refreshable-beans)。| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 下面的示例显示了通过使用 Groovy 动态语言实现的 Spring `org.springframework.validation.Validator`(有关[Validation using Spring’s Validator interface](core.html#validator)接口的讨论,请参见[Validation using Spring’s Validator interface](core.html#validator)): ``` 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.") } } ``` ### 3.4.附加细节 最后一节包含了一些与动态语言支持相关的附加细节。 #### 3.4.1. AOP——建议脚本豆子 你可以使用 Spring AOP 框架来建议脚本化的 bean。 Spring AOP 框架实际上并不知道正在被建议的 Bean 可能是脚本化的 Bean,因此你使用(或旨在使用)的所有 AOP 用例和功能都与脚本化的 bean 一起工作。当你建议使用脚本 bean 时,不能使用基于类的代理。你必须使用[基于接口的代理](core.html#aop-proxying)。 你不限于为脚本 bean 提供建议。还可以用受支持的动态语言编写方面本身,并使用这样的 bean 来建议其他 Spring bean。不过,这确实是对动态语言支持的高级使用。 #### 3.4.2.范围界定 在不是立即显而易见的情况下,脚本 bean 可以以与任何其他 bean 相同的方式进行作用域 Bean。各种``元素上的`scope`属性允许你控制底层脚本 Bean 的作用域,就像它对常规 Bean 所做的那样。(默认作用域是[singleton](core.html#beans-factory-scopes-singleton),就像“常规”bean 一样。 下面的示例使用`scope`属性将 groovy Bean 的作用域定义为[prototype](core.html#beans-factory-scopes-prototype): ``` ``` 有关 Spring 框架中范围支持的完整讨论,请参见[Bean Scopes](core.html#beans-factory-scopes)中的[IOC 容器](core.html#beans)。 #### 3.4.3.`lang`XML 模式 Spring XML 配置中的`lang`元素将用动态语言(如 Groovy 或 BeanShell)编写的对象作为 Spring 容器中的 bean 公开。 在[动态语言支持](#dynamic-language)中全面介绍了这些元素(以及动态语言支持)。有关此支持和`lang`元素的详细信息,请参见该部分。 要使用`lang`模式中的元素,你需要在 Spring XML 配置文件的顶部具有以下前导码。以下代码片段中的文本引用了正确的模式,因此`lang`名称空间中的标记对你是可用的: ``` ``` ### 3.5.更多资源 下面的链接指向关于本章中引用的各种动态语言的更多参考资料: * [Groovy](https://www.groovy-lang.org/)主页 * [BeanShell](https://beanshell.github.io/intro.html)主页 * [JRuby](https://www.jruby.org)主页