语言
1. Kotlin
Spring Framework 为 Kotlin 提供了顶级支持,使开发者几乎可以像 Spring Framework 是原生 Kotlin 框架一样编写 Kotlin 应用程序。参考文档中的大多数代码示例都提供了 Kotlin 版本,同时还包括 Java 版本。
构建Spring应用程序的最简单方法是利用Spring Boot及其针对Kotlin的支持。 专门针对Kotlin的支持。 本全面教程 将教您如何使用start.spring.io构建Spring Boot应用程序。
欢迎加入 #spring 频道的 Kotlin Slack
或者在需要支持时,通过 spring 和 kotlin 作为标签在
Stackoverflow 上提问。
1.1. 要求
Spring Framework 支持 Kotlin 1.3+ 并要求
kotlin-stdlib
(或其变体,例如 kotlin-stdlib-jdk8)
和 kotlin-reflect
存在于类路径中。如果您在
start.spring.io 上引导一个 Kotlin 项目,它们会默认提供。
| Kotlin 内联类 当前尚不支持。 |
Jackson Kotlin模块是必需的,用于使用Jackson对Kotlin类进行序列化或反序列化JSON数据,因此如果需要,请确保将
com.fasterxml.jackson.module:jackson-module-kotlin依赖项添加到您的项目中。
当在类路径中找到时,它会自动注册。 |
1.2. 扩展
Kotlin 扩展 提供了对现有类添加额外功能的能力。Spring 框架的 Kotlin API 使用这些扩展,以向现有的 Spring API 添加新的 Kotlin 特定便利功能。
Spring Framework KDoc API 列出了所有可用的 Kotlin 扩展和 DSL。
请记住,Kotlin 扩展需要被导入才能使用。这意味着,
例如,GenericApplicationContext.registerBean Kotlin 扩展
只有在导入 org.springframework.context.support.registerBean 时才可用。
话虽如此,与静态导入类似,大多数情况下,IDE 应该会自动建议导入。 |
例如,Kotlin内联类型参数
为JVM 泛型类型擦除 提供了一种解决方法,
Spring框架提供了一些扩展以利用此功能。
这使得新的 RestTemplate 从Spring
WebFlux,以及各种其他API的Kotlin API更加完善。
| 其他库,如Reactor和Spring Data,也为它们的API提供了Kotlin扩展,从而整体上提供了更好的Kotlin开发体验。 |
要检索 Java 中 User 个对象的列表,通常会编写以下代码:
Flux<User> users = client.get().retrieve().bodyToFlux(User.class)
使用 Kotlin 和 Spring 框架的扩展,你可以编写如下内容:
val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()
与 Java 一样,Kotlin 中的 users 是强类型,但 Kotlin 的智能类型推断允许使用更简短的语法。
1.3. 空安全
Kotlin 的一个关键特性是 空安全性,
这在编译时干净地处理 null 值,而不是在运行时遇到著名的
NullPointerException。通过空值声明和无需付出包装器(如 Optional)的代价来表达“有值或无值”的语义,这使应用程序更安全。
(Kotlin 允许对可为空的值使用函数式结构。参见此
Kotlin 空安全性全面指南。)
尽管 Java 无法在其类型系统中表达空安全,但 Spring 框架通过在 org.springframework.lang 包中声明的对工具友好的注解提供了整个 Spring 框架 API 的空安全。
默认情况下,Kotlin 中使用的 Java API 类型被识别为
平台类型,
对于这些类型,空检查是放松的。
JSR-305 注解的 Kotlin 支持
和 Spring 空值注解为 Kotlin 开发者提供了整个 Spring 框架 API 的空安全,
其优势是在编译时处理 null 相关的问题。
| 像Reactor或Spring Data这样的库提供了空安全的API来利用此功能。 |
您可以通过添加带有以下选项的 -Xjsr305 编译器标志来配置 JSR-305 检查: -Xjsr305={strict|warn|ignore}。
对于 Kotlin 版本 1.1+,默认行为与 -Xjsr305=warn 相同。
strict 的值要求在从 Spring API 推断的 Kotlin 类型中考虑 Spring Framework API 的空安全性
但应意识到 Spring API 的空性声明可能在小版本之间发生变化,并且未来可能会添加更多的检查。
| 泛型类型参数、可变参数和数组元素的空性目前还不受支持, 但将在未来的版本中加入。请参阅 此讨论 以获取最新信息。 |
1.4. 类和接口
Spring框架支持各种Kotlin结构,例如通过主构造函数实例化Kotlin类、不可变类的数据绑定,以及具有默认值的函数可选参数。
Kotlin 参数名称通过专用的 KotlinReflectionParameterNameDiscoverer 识别,
这允许在不启用 Java 8 -parameters 编译器标志的情况下查找接口方法的参数名称。
您可以将配置类声明为 顶级类或嵌套类,但不能是内部类, 因为后者需要对外部类的引用。
1.5. 注解
Spring 框架还利用 Kotlin 空安全
来确定 HTTP 参数是否为必填项,而无需显式定义
required 属性。这意味着 @RequestParam name: String? 被视为不是必填项,相反,
@RequestParam name: String 被视为必填项。此功能也适用于 Spring 消息处理中的
@Header 注解。
以类似的方式,使用 @Autowired、@Bean 或 @Inject 的 Spring bean 注入会利用此信息来确定 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验证,可能需要使用
注解使用站点目标,
例如 @field:NotNull 或 @get:Size(min=5, max=15),如
此Stack Overflow回答 中所述。 |
1.6. Bean定义DSL
Spring Framework 通过使用 lambda 表达式作为 XML 或 Java 配置(@Configuration 和 @Bean)的替代方式,支持以功能化的方式注册 bean。简而言之,它允许你通过一个充当 FactoryBean 的 lambda 表达式来注册 bean。
此机制非常高效,因为它不需要任何反射或 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 中,使用 reified 类型参数和 GenericApplicationContext 个 Kotlin 扩展,
您可以编写以下内容:
class Foo
class Bar(private val foo: Foo)
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean { Bar(it.getBean()) }
}
当类 Bar 有一个单一构造函数时,你甚至可以只指定 bean 类,
构造函数参数将按类型自动注入:
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean<Bar>()
}
为了允许更声明式的的方法和更简洁的语法,Spring Framework 提供了
一个 Kotlin bean 定义 DSL
它通过一个简洁的声明式 API 声明一个 ApplicationContextInitializer,
这使你可以处理 profiles 和 Environment 以自定义
bean 的注册方式。
在下面的示例中请注意:
-
类型推断通常允许避免为bean引用指定类型,如
ref("bazBean") -
可以使用Kotlin顶级函数,通过可调用引用(如本例中的
bean(::myRouter))来声明bean -
当指定
bean<Bar>()或bean(::myRouter)时,参数将按类型自动注入 -
只有在激活了
foobar配置文件时,才会注册FooBarBean
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)
val myBeans = beans {
bean<Foo>()
bean<Bar>()
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 和
尚未提供对函数式 bean 定义的特定支持,
但可以通过 Spring Boot 的 ApplicationContextInitializer 支持进行实验性使用。
请参阅 此 Stack Overflow 回答
以获取更多详细信息和最新信息。另请参见在 Spring Fu 孵化器 中开发的实验性 Kofu DSL。 |
1.7. Web
1.7.1. 路由 DSL
Spring Framework 随附一个 Kotlin 路由 DSL,有 3 种不同的风格:
-
WebMvc.fn DSL 与 router { }
-
WebFlux.fn 响应式 DSL 与 router { }
-
WebFlux.fn 协程 DSL 与 coRouter { }
这些DSL允许您编写简洁且符合习惯的Kotlin代码,如以下示例所示,以构建一个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 项目 以获取具体示例。
1.7.2. MockMvc DSL
通过 MockMvc 个 Kotlin 扩展提供了一个 Kotlin DSL,以提供更符合 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
,该功能支持 JSR-223 通过使用脚本引擎来渲染模板。
通过利用 scripting-jsr223 个依赖项,可以使用此功能来使用基于 Kotlin 的模板与
kotlinx.html DSL 或 Kotlin 多行插值 String 渲染。
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 示例 项目以获取更多信息。
1.7.4. Kotlin 多平台序列化
从Spring Framework 5.3开始,Kotlin多平台序列化在Spring MVC、Spring WebFlux和Spring Messaging(RSocket)中得到支持。内置支持目前仅针对JSON格式。
要启用它,请按照这些说明添加相关依赖项和插件。
使用 Spring MVC 和 WebFlux 时,如果 Kotlin 序列化和 Jackson 在类路径中,它们将默认配置。
Kotlin 序列化旨在仅序列化带有 @Serializable 注解的 Kotlin 类。
使用 Spring Messaging(RSocket)时,如果希望自动配置,请确保 Jackson、GSON 或 JSONB 不在类路径中,
如果需要 Jackson,请手动配置 KotlinSerializationJsonMessageConverter。
1.8. 协程
Kotlin 协程 是 Kotlin 的轻量级线程,允许以命令式方式编写非阻塞代码。在语言层面,挂起函数为异步操作提供了抽象;而在库层面,kotlinx.coroutines 提供了如
async { }
和类型如 Flow 的功能。
Spring Framework 在以下作用域中提供了对协程的支持:
1.8.1. 依赖项
当 kotlinx-coroutines-core 和 kotlinx-coroutines-reactor 依赖项在类路径中时,启用协程支持:
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. Reactive 如何转换为协程?
对于返回值,从响应式编程到协程 API 的转换如下:
-
fun handler(): Mono<Void>变为suspend fun handler() -
fun handler(): Mono<T>变为suspend fun handler(): T或suspend fun handler(): T?,具体取决于Mono是否可以为空(具有更静态类型的优点) -
fun handler(): Flux<T>变为fun handler(): Flow<T>
对于输入参数:
-
如果不需要惰性,
fun handler(mono: Mono<T>)变为fun handler(value: T),因为可以调用挂起函数来获取值参数。 -
如果需要懒加载,
fun handler(mono: Mono<T>)变为fun handler(supplier: suspend () → T)或fun handler(supplier: suspend () → T?)
Flow 在协程世界中等同于 Flux,适用于热流或冷流、有限流或无限流,主要有以下区别:
-
Flow是基于推送的,而Flux是推送-拉取混合模式 -
背压是通过挂起函数实现的
-
Flow只有一个 挂起的collect方法,而操作符作为 扩展 实现 -
操作符的实现非常简单,这要归功于协程
-
扩展可以用来向
Flow添加自定义运算符 -
集合操作是挂起函数
-
map运算符 支持异步操作(不需要flatMap),因为它接受一个挂起函数参数
阅读此博客文章 使用 Spring、协程和 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<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 {
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 进行视图渲染也受支持。
@Controller
class CoroutinesViewController(banner: Banner) {
@GetMapping("/")
suspend fun render(model: Model): String {
delay(10)
model["banner"] = banner
return "index"
}
}
1.8.4. WebFlux.fn
这是一个通过 coRouter { } 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<User>()))
suspend fun listApi(request: ServerRequest): ServerResponse =
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait(
client.get().uri("...").awaitExchange().awaitBody<User>())
}
1.8.5. 事务
通过 Spring Framework 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<T>.transactional 扩展。
import org.springframework.transaction.reactive.transactional
class PersonRepository(private val operator: TransactionalOperator) {
fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)
private fun findPeople(): Flow<Person> {
// SELECT SQL statement
}
private suspend fun updatePerson(person: Person): Person {
// UPDATE SQL statement
}
}
1.9. Kotlin中的Spring项目
本节提供了一些针对使用 Kotlin 开发 Spring 项目的具体提示和建议。
1.9.1. 默认为最终
默认情况下,Kotlin中的所有类都是final。
open修饰符用于类时,与Java中的final相反:它允许其他人继承此类。
这一点也适用于成员函数,即它们需要被标记为open才能被覆盖。
虽然 Kotlin 的 JVM 友好设计通常与 Spring 无缝配合,但如果未考虑到这一事实,此特定的 Kotlin 功能可能会阻止应用程序启动。这是因为 Spring Bean(例如默认需要在运行时扩展的 @Configuration 注解类)通常由 CGLIB 进行代理。解决方法是在每个由 CGLIB 代理的 Spring Bean 的类和成员函数上添加 open 关键字,这可能会变得很麻烦,并且违背了 Kotlin 保持代码简洁和可预测的原则。
也可以通过使用 @Configuration(proxyBeanMethods = false) 避免配置类的 CGLIB 代理。
有关更多详细信息,请参阅 proxyBeanMethods Javadoc。 |
幸运的是,Kotlin 提供了一个
kotlin-spring
插件(kotlin-allopen 插件的预配置版本),它会自动打开使用以下注解之一进行注解或元注解的类型的类
和其成员函数:
-
@Component -
@Async -
@Transactional -
@Cacheable
元注解支持意味着,使用 @Configuration、@Controller、
@RestController、@Service 或 @Repository 注解的类型会自动被打开,因为这些
注解被 @Component 元注解所注解。
start.spring.io 默认启用
kotlin-spring 插件。因此,实际上,您可以直接编写 Kotlin beans
而无需任何额外的 open 关键字,就像在 Java 中一样。
Spring Framework 文档中的 Kotlin 代码示例并未在类及其成员函数上显式指定
open。这些示例是为使用
kotlin-allopen 插件的项目编写的,因为这是最常用的设置。 |
1.9.2. 使用不可变类实例进行持久化
在 Kotlin 中,将只读属性声明在主构造函数中是方便的,并且被认为是最佳实践,如下例所示:
class Person(val name: String, val age: Int)
您可以选择添加 关键字 data
以使编译器自动从主构造函数中声明的所有属性推导出以下成员:
-
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)需要一个默认构造函数,这会阻止这种设计。幸运的是,有一个解决方法可以避免这种
“默认构造函数的困境”,
因为Kotlin提供了一个 kotlin-jpa
插件,该插件为使用JPA注解标注的类生成合成的无参构造函数。
如果您需要为其他持久化技术利用这种机制,可以配置
the kotlin-noarg
插件。
从Kay发布版开始,Spring Data 支持 Kotlin 不可变类实例,并且如果模块使用 Spring Data 对象映射(如 MongoDB、Redis、Cassandra 等),则不需要 kotlin-noarg 插件。 |
1.9.3. 注入依赖
我们建议尽量使用带有 val 个只读(在可能的情况下为非空)属性 的构造函数注入,
如下面的示例所示:
@Component
class YourBean(
private val mongoTemplate: MongoTemplate,
private val solrClient: SolrClient
)
带有单个构造函数的类会自动自动装配其参数。
这就是为什么在上面显示的示例中不需要显式的 @Autowired constructor 的原因。 |
如果您确实需要使用字段注入,可以使用 lateinit var 结构,
如下面的示例所示:
@Component
class YourBean {
@Autowired
lateinit var mongoTemplate: MongoTemplate
@Autowired
lateinit var solrClient: SolrClient
}
1.9.4. 注入配置属性
在 Java 中,你可以通过使用注解(例如 @Value("${property}"))注入配置属性。
但是在 Kotlin 中,$ 是一个保留字符,用于
字符串插值。
因此,如果您希望在Kotlin中使用@Value注解,需要通过编写@Value("\${property}")来转义$字符。
如果你使用 Spring Boot,你可能应该使用
@ConfigurationProperties
而不是 @Value 注解。 |
作为另一种选择,您可以通过声明以下配置 Bean 来自定义属性占位符前缀:
@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
}
您可以自定义现有代码(例如 Spring Boot 指标端点或 @LocalServerPort)
,该代码使用 ${…} 语法,并通过配置 Bean,如下例所示:
@Bean
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
setIgnoreUnresolvablePlaceholders(true)
}
@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
1.9.5. 已检查异常
Java 和 Kotlin 异常处理
非常接近,主要区别在于 Kotlin 将所有异常都视为未检查异常。然而,当使用代理对象(例如带有 @Transactional 注解的类或方法)时,默认会将抛出的已检查异常包装在 UndeclaredThrowableException 中。
为了像Java中那样获取原始抛出的异常,方法应使用
@Throws
进行注解,以明确指定抛出的检查型异常(例如 @Throws(IOException::class))。
1.9.6. 注解数组属性
Kotlin 注解与 Java 注解大部分相似,但数组属性(在 Spring 中广泛使用)的行为有所不同。如 Kotlin 文档 中所述,您可以省略 value 属性名称,与其他属性不同,可以将其指定为 vararg 参数。
要理解这意味着什么,请考虑 @RequestMapping(这是最广泛使用的Spring注解之一)作为一个例子。这个Java注解的声明如下:
public @interface RequestMapping {
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
RequestMethod[] method() default {};
// ...
}
@RequestMapping 的典型用例是将处理方法映射到特定路径和方法。在 Java 中,您可以为注解数组属性指定一个值,并且它会自动转换为数组。
这就是为什么可以编写
@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. 测试
| 如果使用 Spring Boot,请参阅 相关文档。 |
构造器注入
如在专门的部分中所述,
JUnit 5 允许通过构造函数注入 beans,这在使用 Kotlin 时非常有用,
以便使用 val 而不是 lateinit var。您可以使用
@TestConstructor(autowireMode = AutowireMode.ALL)
来为所有参数启用自动注入。
@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 允许您在反引号(`)之间指定有意义的测试函数名称。
从 JUnit 5 开始,Kotlin 测试类可以使用 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
注解来启用测试类的单例实例化,这允许在非静态方法上使用 @BeforeAll
和 @AfterAll
注解,这非常适合 Kotlin。
您也可以通过一个带有 junit-platform.properties 属性的 PER_CLASS 文件将默认行为更改为 junit.jupiter.testinstance.lifecycle.default = per_class。
以下示例演示了非静态方法上的 @BeforeAll 和 @AfterAll 注释:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class IntegrationTests {
val application = Application(8181)
val client = WebClient.create("http://localhost:8181")
@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()
}
}
类似规范的测试
你可以使用 JUnit 5 和 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)
}
}
}
1.10. 入门
学习如何使用Kotlin构建Spring应用程序的最简单方法是遵循 专门的教程。
1.10.1. start.spring.io
开始新Spring框架项目的最简单方法是在 start.spring.io 上创建一个新的Spring Boot 2项目。
1.10.2. 选择 Web 风格
Spring Framework 现在包含两种不同的 Web 堆栈: Spring MVC 和 Spring WebFlux.
Spring WebFlux 在你希望创建处理延迟、长连接、流式场景的应用程序,或者希望使用 Web 函数式 Kotlin DSL 时是推荐的选择。
对于其他使用场景,尤其是当你使用阻塞技术如 JPA 时,Spring MVC 及其基于注解的编程模型是推荐的选择。
1.11. 资源
我们建议学习如何使用 Kotlin 和 Spring 框架构建应用程序的人参考以下资源:
-
Kotlin Slack(设有专门的 #spring 频道)
1.11.1. 示例
以下Github项目提供了你可以学习甚至可能扩展的示例:
-
spring-boot-kotlin-demo: 传统的Spring Boot和Spring Data JPA项目
-
mixit: Spring Boot 2,WebFlux,以及响应式 Spring Data MongoDB
-
spring-kotlin-functional: 独立的WebFlux和函数式Bean定义DSL
-
spring-kotlin-fullstack:基于 WebFlux 的 Kotlin 全栈示例,前端使用 Kotlin/JS(而非 JavaScript 或 TypeScript)
-
spring-petclinic-kotlin:Spring PetClinic 示例应用程序的 Kotlin 版本
-
spring-kotlin-deepdive: 从 Boot 1.0 和 Java 迁移到 Boot 2.0 和 Kotlin 的逐步指南
-
spring-cloud-gcp-kotlin-app-sample: 使用 Google Cloud Platform 集成的 Spring Boot
2. Apache Groovy
Groovy 是一种功能强大、可选类型且动态的语言,具有静态类型和静态编译功能。它提供了简洁的语法,并能与任何现有的 Java 应用程序无缝集成。
Spring 框架提供了一个专用的 ApplicationContext,它支持基于 Groovy 的 Bean 定义 DSL。有关更多详细信息,请参见
基于 Groovy 的 Bean 定义 DSL。
对Groovy的进一步支持,包括用Groovy编写的beans、可刷新的脚本beans等,在<a t="C0">动态语言支持</a>中可用。
3. 动态语言支持
Spring 提供了全面的支持,用于使用通过动态语言(如 Groovy)定义的类和对象。这种支持使您可以用受支持的动态语言编写任意数量的类,并让 Spring 容器透明地实例化、配置和依赖注入这些对象。
Spring的脚本支持主要针对Groovy和BeanShell。除了这些特定支持的语言之外,JSR-223脚本机制也用于与任何JSR-223兼容的语言提供者进行集成(自Spring 4.2起),例如JRuby。
您可以找到此动态语言支持可以立即有用的完整示例 情景。
3.1. 第一个示例
本章的大部分内容旨在详细描述动态语言支持。在深入探讨动态语言支持的所有细节之前,我们先看一个用动态语言定义的 bean 的快速示例。第一个 bean 使用的动态语言是 Groovy。(此示例的基础来自 Spring 测试套件。如果您想查看其他任何支持的语言中的等效示例,请查看源代码)。
下一个示例显示了 Messenger 接口,Groovy bean 将要实现该接口。请注意,此接口是用纯 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中实现了<code>0</code>接口:
// 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 Schema前导。您还需要使用Spring 有关基于架构的配置的更多信息,请参阅 基于 XML 架构的配置。 |
最后,下面的示例显示了影响将Groovy定义的Messenger实现注入到DefaultBookingService类实例中的bean定义:
<?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>
The bookingService bean (a DefaultBookingService) now can 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代码片段是不言自明的,但如果它不是,也不必过于担心。继续阅读,了解前面配置的详细原因和背景。
3.2. 定义由动态语言支持的 Bean
本节准确描述了如何在任何支持的动态语言中定义由Spring管理的Bean。
请注意,本章并不试图解释所支持的动态语言的语法和习惯用法。例如,如果您想使用 Groovy 来编写应用程序中的某些类,我们假设您已经了解 Groovy。如果需要有关这些动态语言的更多信息,请参阅本章末尾的 进一步资源。
3.2.1. 常见概念
使用动态语言支持的 Bean 的步骤如下:
-
为动态语言源代码编写测试(自然地)。
-
然后编写动态语言的源代码本身。
-
通过在XML配置中使用适当的
<lang:language/>元素来定义基于动态语言的bean(您可以通过使用Spring API以编程方式定义此类bean,尽管您需要查阅源代码以了解如何执行此操作,因为本章不涉及此类高级配置)。 请注意,这是一个迭代步骤。您需要为每个动态语言源文件至少定义一个bean(尽管多个bean定义可以引用同一个源文件)。
前两步(测试和编写你的动态语言源文件)超出了本章的范围。请参阅你所选择的动态语言的语言规范和参考手册,并开始开发你的动态语言源文件。不过,你首先还是想阅读本章的其余部分,因为Spring的动态语言支持对你动态语言源文件的内容做了一些(小的)假设。
<lang:language/> 元素
列表中的最后一步在上一节的前一节中涉及定义基于动态语言的bean定义,每个您想要配置的bean都要定义一个(这与普通的JavaBean配置没有区别)。然而,您不需要指定由容器实例化和配置的类的全限定类名,而是可以使用<lang:language/>元素来定义基于动态语言的bean。
每种支持的语言都有一个对应的 <lang:language/> 元素:
-
<lang:groovy/>(Groovy) -
<lang:bsh/>(BeanShell) -
<lang:std/>(JSR-223,例如使用 JRuby)
确切的属性和子元素可用性取决于 bean 是在哪种语言中定义的(本章后面的特定于语言的部分详细说明了这一点)。
可刷新的 Bean
动态语言支持在Spring中的一个(也许是唯一的)最有价值的增强功能是“可刷新的Bean”特性。
一个可刷新的 Bean 是一种由动态语言支持的 Bean。通过少量的配置,由动态语言支持的 Bean 可以监控其底层源文件资源的变化,并在动态语言源文件发生变化时重新加载自身(例如,当您在文件系统中编辑并保存文件更改时)。
这使您可以在应用程序中部署任意数量的动态语言源文件,配置Spring容器以使用本章描述的机制,由动态语言源文件支持创建Bean,并且(在需求变化或某些其他外部因素出现后)编辑动态语言源文件,使他们所做的任何更改都能反映在由该更改的动态语言源文件支持的Bean中。无需关闭正在运行的应用程序(对于Web应用程序而言,也无需重新部署)。经修改的基于动态语言的Bean会从更改后的动态语言源文件中获取新的状态和逻辑。
| 此功能默认是关闭的。 |
现在我们可以看一个例子,了解使用可刷新的Bean有多么简单。要启用可刷新的Bean功能,您必须在Bean定义的<lang:language/>元素上指定一个额外的属性。因此,如果我们继续使用本章前面的示例,下面的例子将展示我们在Spring XML配置中需要进行哪些更改以实现可刷新的Bean:
<beans>
<!-- this bean is now 'refreshable' due to the presence of the 'refresh-check-delay' attribute -->
<lang:groovy id="messenger"
refresh-check-delay="5000" <!-- switches refreshing on with 5 seconds between checks -->
script-source="classpath:Messenger.groovy">
<lang:property name="message" value="I Can Do The Frug" />
</lang:groovy>
<bean id="bookingService" class="x.y.DefaultBookingService">
<property name="messenger" ref="messenger" />
</bean>
</beans>
你所需要做的就是这些。在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());
}
}
假设在本示例中,所有对getMessage()的Messenger实现的调用都必须更改,使得消息被引号包围。以下列表显示了当程序执行暂停时,您(开发者)应对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。
在对源文件进行更改并保存后,程序继续执行,
对动态语言支持的 getMessage() 实现调用 Messenger 方法的结果是 'I Can Do The Frug'(注意额外引号的包含)。
如果在 refresh-check-delay 值的时间窗口内发生脚本更改,则不会触发刷新。对脚本的更改实际上直到调用基于动态语言的 bean 的方法时才会被检测到。只有在对基于动态语言的 bean 调用方法时,才会检查其底层脚本源是否已更改。与刷新脚本相关的任何异常(例如遇到编译错误或发现脚本文件已被删除)会导致致命异常传播到调用代码。
前面描述的可刷新Bean行为不适用于使用<lang:inline-script/>元素符号定义的动态语言源文件(参见内联动态语言源文件)。此外,它仅适用于可以实际检测到底层源文件更改的Bean(例如,通过检查存在于文件系统上的动态语言源文件的最后修改日期的代码)。
内联动态语言源文件
动态语言支持还可以处理直接嵌入Spring bean定义中的动态语言源文件。更具体地说,<lang:inline-script/>元素允许您在Spring配置文件内部直接定义动态语言源。一个例子可以说明内联脚本功能的工作方式:
<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实现。使用内联源代码只需片刻即可完成。(参见脚本验证器以获取此类示例。)
了解动态语言支持的 Bean 中的构造函数注入
与 Spring 的动态语言支持有关,有一件非常重要的事情需要留意。即,目前你无法为基于动态语言的 Bean 提供构造函数参数(因此,基于动态语言的 Bean 也不支持构造函数注入)。为了使对构造函数和属性的特殊处理完全清晰,以下代码和配置的混合使用是无效的:
// 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
}
<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>
在实际应用中,这种限制并没有看起来那么严重,因为设值注入是绝大多数开发人员偏好的注入方式(我们暂且将是否这是好事的讨论留到另一天)。
3.2.2. Groovy Bean
本节描述如何在Spring中使用Groovy中定义的beans。
Groovy首页包含以下描述:
“Groovy 是一种适用于 Java 2 平台的敏捷动态语言,它具有人们在 Python、Ruby 和 Smalltalk 等语言中非常喜欢的许多特性,使用类似 Java 的语法,使这些特性对 Java 开发人员可用。”
如果您从头到尾阅读了这一章,您已经 看过一个示例,该示例使用了基于Groovy动态语言的 bean。现在考虑另一个示例(再次使用Spring测试套件中的一个示例):
package org.springframework.scripting;
public interface Calculator {
int add(int x, int y);
}
以下示例在Groovy中实现了<code>0</code>接口:
// from the file 'calculator.groovy'
package org.springframework.scripting.groovy
class GroovyCalculator implements Calculator {
int add(int x, int y) {
x + y
}
}
以下 bean 定义使用了在 Groovy 中定义的计算器:
<!-- from the file 'beans.xml' -->
<beans>
<lang:groovy id="calculator" script-source="classpath:calculator.groovy"/>
</beans>
最后,以下这个小型应用程序测试了前面的配置:
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。
(有关更有趣的示例,请参阅动态语言展示项目中的更复杂示例,或查看本章后面的例子 场景)。
你不能在Groovy源文件中定义多个类。虽然这在Groovy中是完全合法的,但(可以说)是一种不好的做法。为了保持一致的方法,根据Spring团队的意见,你应该遵守标准Java惯例,即每个源文件只定义一个(public)类。
通过回调自定义Groovy对象
GroovyObjectCustomizer 接口是一个回调,它允许你将额外的创建逻辑插入到创建基于 Groovy 的 bean 的过程中。例如,该接口的实现可以调用任何必需的初始化方法、设置一些默认属性值,或指定自定义的 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是非常简单的,如下例所示:
<!-- 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 功能,如下例所示:
<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"/>
你也可以在Spring的CompilationCustomizer位置指定一个Groovy ImportCustomizer(例如一个CompilerConfiguration)
或者甚至一个完整的Groovy GroovyObjectCustomizer对象。此外,你可以在GroovyClassLoader级别上为你的bean设置一个通用的ConfigurableApplicationContext.setClassLoader,并进行自定义配置;
这也会导致共享的GroovyClassLoader使用,因此在有大量脚本化bean的情况下(避免每个bean都单独实例化一个GroovyClassLoader)是推荐的做法。 |
3.2.3. BeanShell Bean
本节描述如何在Spring中使用BeanShell beans。
该 BeanShell 主页 包含以下 描述:
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会创建一个JDK动态代理,该代理实现了script-interfaces属性值中指定的所有接口的<lang:bsh>元素(这就是为什么您必须在属性值中至少提供一个接口,因此在使用基于BeanShell的bean时,必须根据接口进行编程)。这意味着对基于BeanShell的对象的每个方法调用都会通过JDK动态代理调用机制。
现在我们可以展示一个使用基于BeanShell的bean的完整示例,该bean实现了本章中之前定义的Messenger接口。我们再次展示Messenger接口的定义:
package org.springframework.scripting;
public interface Messenger {
String getMessage();
}
下面的示例显示了 BeanShell 的“实现”(我们在这里松散地使用该术语)
的 Messenger 接口:
String message;
String getMessage() {
return message;
}
void setMessage(String aMessage) {
message = aMessage;
}
以下示例显示了定义上述“类”的一个“实例”的 Spring XML(再次说明,我们在这里非常宽松地使用这些术语):
<lang:bsh id="messageService" script-source="classpath:BshMessenger.bsh"
script-interfaces="org.springframework.scripting.Messenger">
<lang:property name="message" value="Hello World!" />
</lang:bsh>
查看 场景 了解可能需要使用基于 BeanShell 的 beans 的一些情况。
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”功能。有关此功能的完整说明,请参阅 可刷新的Bean。 |
以下示例显示了一个通过使用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())
}
}
<lang:groovy id="fortune"
refresh-check-delay="3000"
script-source="/WEB-INF/groovy/FortuneController.groovy">
<lang:property name="fortuneService" ref="fortuneService"/>
</lang:groovy>
3.3.2. 脚本验证器
使用Spring进行应用开发的另一个领域,可能从动态语言支持的Bean所提供的灵活性中受益,那就是验证。与普通的Java相比,使用一种弱类型动态语言(可能还支持内联正则表达式)来表达复杂的验证逻辑可能会更加容易。
再次说明,将验证器作为动态语言支持的 Bean 进行开发,允许您通过编辑和保存一个简单的文本文件来更改验证逻辑。任何此类更改(根据配置)会自动反映在运行中的应用程序执行中,而无需重新启动应用程序。
| 要实现对任何基于动态语言的bean的更改的自动“获取”,您必须启用“可刷新的bean”功能。有关此功能的完整详细说明,请参见 可刷新的Bean。 |
以下示例显示了一个使用Groovy动态语言实现的Spring org.springframework.validation.Validator
(有关Validator接口的讨论,请参见使用Spring的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 — 对脚本化Bean进行通知
您可以使用Spring AOP框架来建议脚本化Bean。Spring AOP框架实际上并不知道正在被建议的Bean可能是一个脚本化Bean,因此您所使用的(或旨在使用的)所有AOP用例和功能都与脚本化Bean兼容。当您建议脚本化Bean时,不能使用基于类的代理。您必须使用基于接口的代理。
你不仅限于对脚本化的Bean进行建议。你也可以在支持的动态语言中编写切面本身,并使用这些Bean来对其他Spring Bean进行建议。不过,这实际上是对动态语言支持的一种高级用法。
3.4.2. 作用域
如果尚未明显,脚本化的Bean可以以与任何其他Bean相同的方式进行作用域设置。各种scope元素上的<lang:language/>属性允许您控制底层脚本化Bean的作用域,就像对普通Bean所做的那样。(默认作用域是单例,与“普通”Bean一样。)
以下示例使用 scope 属性来定义一个作用域为
原型 的 Groovy Bean:
<?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>
3.4.3. lang XML 架构
Spring XML配置中的<code>0</code>元素用于将用动态语言(如Groovy或BeanShell)编写的对象作为Spring容器中的bean公开。
这些元素(以及动态语言支持)在动态语言支持部分有全面的说明。有关此支持以及lang元素的详细信息,请参阅该部分。
要使用 lang 架构中的元素,您需要在 Spring XML 配置文件的顶部包含以下引言。以下片段中的文本引用了正确的架构,以便您能够使用 lang 命名空间中的标签:
<?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>