1. 科特林
Spring Framework 为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序几乎就像 Spring Framework 是原生的 Kotlin 框架一样。 参考文档的大多数代码示例是 除了 Java 之外,还在 Kotlin 中提供。
使用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring Boot 和 其专用的 Kotlin 支持。这个全面的教程将教你如何使用 start.spring.io 使用 Kotlin 构建 Spring Boot 应用程序。
如果您需要支持,请随时加入 Kotlin Slack 的
#spring 频道,或者在 Stackoverflow 上使用 和 as
标签提问。spring
kotlin
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 Framework Kotlin API 使用这些扩展为现有 Spring API 添加新的特定于 Kotlin 的便利性。
Spring Framework KDoc API 列表 并记录了所有可用的 Kotlin 扩展和 DSL。
请记住,需要导入
Kotlin 扩展才能使用。这意味着,
例如,Kotlin 扩展
仅当导入时才可用。
也就是说,与静态导入类似,在大多数情况下,IDE 应该自动建议导入。GenericApplicationContext.registerBean org.springframework.context.support.registerBean
|
例如,Kotlin reified 类型参数为 JVM 泛型类型擦除提供了一种解决方法,
Spring Framework 提供了一些扩展来利用此功能。
这允许一个更好的 Kotlin API ,用于 Spring 的新功能
WebFlux 以及各种其他 API。RestTemplate
WebClient
其他库,如 Reactor 和 Spring Data,也提供了 Kotlin 扩展 为他们的 API,从而提供更好的整体 Kotlin 开发体验。 |
要在 Java
中检索对象列表,通常需要编写以下内容:User
Flux<User> users = client.get().retrieve().bodyToFlux(User.class)
使用 Kotlin 和 Spring Framework 扩展,您可以改为编写以下内容:
val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()
与 Java 一样,Kotlin 是强类型的,但
Kotlin 的巧妙类型推断允许
用于更短的语法。users
1.3. 零安全
Kotlin 的主要功能之一是零安全,
它在编译时干净地处理值,而不是在运行时碰到著名的值。这通过可空性使应用程序更安全
声明和表达“有值或无值”的语义,而无需支付包装器的成本,例如 .
(Kotlin 允许使用具有可为 null 值的函数结构。请参阅此 Kotlin
空安全综合指南。null
NullPointerException
Optional
尽管 Java 不允许在其类型系统中表达
null-safety,但 Spring Framework
通过包中声明的工具友好注释提供整个 Spring Framework API 的 null 安全性。
默认情况下,Kotlin 中使用的 Java API 中的类型被识别为平台类型,
放宽了 null 检查。Kotlin 对 JSR-305 注解的支持和 Spring 可空性注解为
Kotlin 开发人员提供了整个 Spring Framework API 的空安全性,
具有在编译时处理相关问题的优点。org.springframework.lang
null
Reactor 或 Spring Data 等库提供了 null 安全 API 来利用此功能。 |
您可以通过添加编译器标志来配置
JSR-305 检查,如下所示
选项:。-Xjsr305
-Xjsr305={strict|warn|ignore}
对于 kotlin 版本 1.1+,默认行为与
相同。
该值是考虑 Spring Framework API null 安全性所必需的
在 Kotlin 类型中,从 Spring API 推断出来,但应该在知道 Spring 的情况下使用
API 可为 null 性声明甚至可以在次要版本之间演变,并且更多的检查可能会
将来添加。-Xjsr305=warn
strict
尚不支持泛型类型参数、varargs 和数组元素可为 null, 但应该在即将发布的版本中。有关最新信息,请参阅此讨论。 |
1.4. 类和接口
Spring Framework 支持各种 Kotlin 结构,例如实例化 Kotlin 类 通过主构造函数、不可变类、数据绑定和函数可选参数 替换为默认值。
Kotlin 参数名称通过专用的 、
它允许查找接口方法参数名称,而无需在编译期间启用 Java 8 编译器标志。KotlinReflectionParameterNameDiscoverer
-parameters
您可以将配置类声明为顶级或嵌套的,但不是内部的, 因为后者需要对外部类的引用。
1.5. 注解
Spring Framework 还利用 Kotlin null-safety 来确定是否需要 HTTP 参数,而无需显式
定义属性。这意味着被对待
不是必需的,反之则被视为必需的。
Spring Messaging 注解也支持此功能。required
@RequestParam name:
String?
@RequestParam name: String
@Header
以类似的方式,Spring Bean 注射用 、
或 使用
此信息用于确定是否需要 Bean。@Autowired
@Bean
@Inject
例如,表示 Bean
的类型必须在应用程序上下文中注册,如果这样的 Bean 不存在,则不会引发错误。@Autowired
lateinit var thing: Thing
Thing
@Autowired lateinit var thing:
Thing?
遵循相同的原则,意味着
必须在应用程序上下文中注册 type 的 bean,而
类型可能存在,也可能不存在。相同的行为也适用于自动连接的构造函数参数。@Bean fun
play(toy: Toy, car: Car?) = Baz(toy, Car)
Toy
Car
如果对具有属性或主构造函数的类使用
Bean 验证
参数,您可能需要使用 annotation use-site targets,
例如 或 ,如此 Stack Overflow 响应中所述。@field:NotNull @get:Size(min=5,
max=15) |
1.6. Bean 定义 DSL
Spring Framework 支持使用 lambda
以函数方式注册 Bean
作为 XML 或 Java 配置 ( 和 ) 的替代方法。简而言之
它允许您使用充当 .
这种机制非常有效,因为它不需要任何反射或 CGLIB
代理。@Configuration
@Bean
FactoryBean
例如,在 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 中,使用统一的类型参数和
Kotlin 扩展,
您可以改为编写以下内容:GenericApplicationContext
class Foo
class Bar(private val foo: Foo)
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean { Bar(it.getBean()) }
}
当类具有单个构造函数时,您甚至可以只指定
Bean 类,
构造函数参数将按类型自动连接:Bar
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean<Bar>()
}
为了允许更声明性的方法和更简洁的语法,Spring
Framework 提供了
一个 Kotlin bean 定义 DSL 它通过一个干净的声明性 API
声明一个,
这使您可以处理配置文件和自定义
Bean 是如何注册的。ApplicationContextInitializer
Environment
在以下示例中,请注意:
-
类型推断通常允许避免为 Bean 引用指定类型,例如
ref("bazBean")
-
可以使用 Kotlin 顶级函数通过可调用引用来声明 bean,如本例所示
bean(::myRouter)
-
指定 或 时,参数按类型自动接线
bean<Bar>()
bean(::myRouter)
-
仅当配置文件处于活动状态时,才会注册 Bean
FooBar
foobar
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
是编程的,这意味着它允许自定义 Bean 的注册逻辑
通过表达式、循环或任何其他 Kotlin 结构。if for |
然后,您可以使用此函数在应用程序上下文中注册
bean。
如以下示例所示:beans()
val context = GenericApplicationContext().apply {
myBeans.initialize(this)
refresh()
}
Spring
Boot 基于 JavaConfig,尚未提供对函数式 Bean 定义的特定支持,
但你可以通过 Spring Boot 的支持实验性地使用函数式 Bean 定义。
有关更多详细信息和最新信息,请参阅此 Stack Overflow 答案。另请参阅在Spring Fu孵化器中开发的实验性Kofu DSL。ApplicationContextInitializer
|
1.7. 网页
1.7.1. 路由器DSL
Spring Framework 附带了一个 Kotlin 路由器 DSL,提供 3 种风格:
-
WebMvc.fn DSL 与路由器 { }
-
WebFlux.fn 使用 coRouter 的协程 DSL { }
这些 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 是编程的,这意味着它允许自定义 Bean 的注册逻辑
通过表达式、循环或任何其他 Kotlin 结构。这可能很有用
当您需要根据动态数据(例如,从数据库)注册路由时。if for
|
有关具体示例,请参阅 MiXiT 项目。
1.7.2. MockMvc DSL的
Kotlin DSL 是通过 Kotlin
扩展提供的,以便提供更多
惯用的 Kotlin API,并允许更好的可发现性(不使用静态方法)。MockMvc
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
使用脚本引擎渲染模板。
通过利用依赖关系,它
可以使用此功能通过 kotlinx.html DSL 或 Kotlin 多行插值来渲染基于
Kotlin 的模板。scripting-jsr223
String
build.gradle.kts
dependencies {
runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
配置通常使用 和 bean
完成。ScriptTemplateConfigurer
ScriptTemplateViewResolver
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 序列化旨在仅序列化带有 注释的 Kotlin 类。
使用 Spring Messaging (RSocket),如果要进行自动配置,请确保 Jackson、GSON 或 JSONB 都不在类路径中,
如果需要 Jackson,请手动配置。@Serializable
KotlinSerializationJsonMessageConverter
1.8. 协程
Kotlin 协程是 Kotlin
轻量级线程允许以命令式方式编写非阻塞代码。在语言方面,
挂起函数为异步操作提供抽象,而在库端,kotlinx.coroutines 提供 async { }
等函数和 Flow
等类型。
Spring Framework 在以下范围内提供对协程的支持:
-
Spring MVC 和 WebFlux 中的挂起函数支持
@Controller
-
WebFlux.fn coRouter { } DSL
-
RSocket 带注释方法中的挂起函数和支持
Flow
@MessageMapping
-
RSocketRequester
的扩展
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 到协程 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>
对于输入参数:
-
如果不需要延迟,则成为,因为可以调用挂起函数来获取 value 参数。
fun handler(mono: Mono<T>)
fun handler(value: T)
-
如果需要懒惰,则变成或
fun handler(mono: Mono<T>)
fun handler(supplier: suspend () → T)
fun handler(supplier: suspend () → T?)
在协程世界中,流动
是等价的,适用于热流或冷流、有限流或无限流,主要区别如下:Flux
阅读这篇关于使用 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()
}
}
还支持使用 a
进行视图渲染。@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 项目
本节提供了一些对开发 Spring 项目有价值的具体提示和建议 在科特林。
1.9.1. 默认为 Final
默认情况下,Kotlin 中的所有类都是 final
。
类的修饰符与 Java 的相反:它允许其他人从这个继承
类。这也适用于成员函数,因为它们需要标记为要重写。open
final
open
虽然 Kotlin 的 JVM 友好设计通常与
Spring 无摩擦,但 Kotlin 的这一特定功能
如果不考虑这一事实,可以阻止应用程序启动。这是因为
Spring bean(例如带注释的类,默认情况下需要在运行时进行扩展以进行技术
原因)通常由 CGLIB 代理。解决方法是在每个类上添加一个关键字,然后
由 CGLIB 代理的 Spring Bean 的成员函数,它可以
很快就会变得痛苦,并且违背了 Kotlin
保持代码简洁和可预测的原则。@Configuration
open
也可以通过使用来避免配置类的
CGLIB 代理。
有关更多详细信息,请参阅 proxyBeanMethods Javadoc。@Configuration(proxyBeanMethods
= false) |
幸运的是,Kotlin 提供了一个 kotlin-spring
插件(插件的预配置版本),可以自动打开类
以及使用以下项之一进行批注或元批注的类型的成员函数
附注:kotlin-allopen
-
@Component
-
@Async
-
@Transactional
-
@Cacheable
元注释支持意味着用 、 、 或
注释的类型会自动打开,因为这些
批注是用 进行元批注的。@Configuration
@Controller
@RestController
@Service
@Repository
@Component
start.spring.io 使
默认的插件。因此,在实践中,您可以编写 Kotlin bean
没有任何其他关键字,就像在 Java 中一样。kotlin-spring
open
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 注释注释的类生成合成的无参数构造函数。
如果需要将这种机制用于其他持久性技术,可以配置
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 中,您可以使用注解(例如
)注入配置属性。
但是,在 Kotlin 中,是用于字符串插值的保留字符。@Value("${property}")
$
因此,如果你想在 Kotlin
中使用注解,你需要通过编写 .@Value
$
@Value("\${property}")
如果您使用
Spring Boot,您可能应该使用 @ConfigurationProperties
而不是注释。@Value |
或者,您可以通过声明 以下配置 Bean:
@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
}
您可以自定义现有代码(例如
Spring Boot 执行器或 )
使用语法和配置 Bean,如以下示例所示:@LocalServerPort
${…}
@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
要理解这意味着什么,请考虑(这是最广泛的之一
使用Spring注解)为例。此 Java 注解声明如下:@RequestMapping
public @interface RequestMapping {
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
RequestMethod[] method() default {};
// ...
}
的典型用例是将处理程序方法映射到特定路径
和方法。在 Java 中,您可以为注释数组属性指定单个值,
它会自动转换为数组。@RequestMapping
这就是为什么可以写 or
.@RequestMapping(value = "/toys", method = RequestMethod.GET)
@RequestMapping(path
= "/toys", method = RequestMethod.GET)
但是,在 Kotlin 中,您必须写成
or(方括号需要
使用命名数组属性指定)。@RequestMapping("/toys", method =
[RequestMethod.GET])
@RequestMapping(path = ["/toys"], method =
[RequestMethod.GET])
此特定属性(最常见的属性)的替代方法是
使用快捷方式批注,例如 、 等。method
@GetMapping
@PostMapping
如果未指定该属性,则所有
HTTP 方法都将
要匹配,而不仅仅是方法。@RequestMapping method GET
|
1.9.7. 测试
如果您使用的是 Spring Boot,请参阅此相关文档。 |
构造函数注入
如专用部分所述,
JUnit 5 允许构造函数注入 bean,这在 Kotlin 中非常有用
以便使用代替 .您可以使用 @TestConstructor(autowireMode
= AutowireMode.ALL)
为所有参数启用自动布线。val
lateinit
var
@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 测试类可以使用注解来启用测试类的单个实例化,这允许在非静态方法上使用和注解,这非常适合
Kotlin。`
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@BeforeAll
@AfterAll
您还可以将默认行为更改为
thanks to a file with a property.PER_CLASS
junit-platform.properties
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
在 Kotlin 中启动新的 Spring Framework 项目的最简单方法是创建一个新的 Spring 在 start.spring.io 上启动 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 全栈示例,使用 Kotlin2js 作为前端而不是 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:Spring Boot 与 Google Cloud Platform 集成
2. 阿帕奇 Groovy
Groovy 是一种功能强大、可选类型化的动态语言,具有静态类型和静态 编译功能。它提供了简洁的语法,并与任何 现有的 Java 应用程序。
Spring Framework 提供了一个专用的,支持基于
Groovy 的
Bean 定义 DSL。有关详细信息,请参见 Groovy Bean 定义
DSL。ApplicationContext
对 Groovy 的进一步支持,包括用 Groovy 编写的 bean、可刷新的脚本 bean、 动态语言支持中提供了更多内容。
3. 动态语言支持
Spring 为使用类和对象提供了全面的支持。 通过在 Spring 中使用动态语言(例如 Groovy)来定义。这种支持使 你用受支持的动态语言编写任意数量的类,并拥有 Spring 容器透明地实例化、配置和依赖注入生成的 对象。
Spring 的脚本支持主要针对 Groovy 和 BeanShell。超越这些 特别支持的语言,支持 JSR-223 脚本机制 用于与任何支持 JSR-223 的语言提供程序集成(从 Spring 4.2 开始), 例如 JRuby。
您可以找到这种动态语言支持的完整工作示例 在场景中立即有用。
3.1. 第一个例子
本章的大部分内容是关于描述 细节。在深入了解动态语言支持的所有细节之前, 我们看一个用动态语言定义的 Bean 的简单示例。动态 第一个 Bean 的语言是 Groovy。(此示例的基础取自 春季测试套件。如果您想在任何其他示例中查看等效示例 支持的语言,看看源代码)。
下一个示例显示了 Groovy bean
将要访问的接口
实现。请注意,此接口是用纯 Java 定义的。依赖对象
注入的参考是不知道底层的
实现是一个 Groovy
脚本。以下列表显示了该接口:Messenger
Messenger
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,请
需要将 XML 模式前导码放在 Spring XML 配置文件的顶部。
您还需要使用 Spring 实现作为 IoC
容器。支持使用带有普通实现的动态语言支持的 bean,但您必须管理 Spring 内部的管道
来做到这一点。 有关基于架构的配置的更多信息,请参见基于 XML 架构的配置。 |
最后,以下示例显示了影响注入
Groovy 定义的实现到类的实例中:Messenger
DefaultBookingService
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">
<!-- this is the bean definition for the Groovy-backed Messenger implementation -->
<lang:groovy id="messenger" script-source="classpath:Messenger.groovy">
<lang:property name="message" value="I Can Do The Frug" />
</lang:groovy>
<!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger -->
<bean id="bookingService" class="x.y.DefaultBookingService">
<property name="messenger" ref="messenger" />
</bean>
</beans>
bean (a )
现在可以正常使用其私有成员变量,因为注入其中的实例是
一个实例。这里没有什么特别的事情发生——只是普通的 Java 和
普通的时髦。bookingService
DefaultBookingService
messenger
Messenger
Messenger
希望前面的 XML 代码段是不言自明的,但如果不是,请不要过度担心。 请继续阅读有关上述配置的原因和原因的深入详细信息。
3.2. 定义由动态语言支持的 Bean
本节将准确描述如何在任何 支持的动态语言。
请注意,本章并不试图解释支持的语法和习语 动态语言。例如,如果要使用 Groovy 编写某些类 在您的应用程序中,我们假设您已经了解 Groovy。如果您需要更多详细信息 关于动态语言本身,请参见 本章。
3.2.1. 常用概念
使用动态语言支持的 Bean 所涉及的步骤如下:
-
(自然地)编写动态语言源代码的测试。
-
然后编写动态语言源代码本身。
-
使用 XML 配置中的相应元素定义动态语言支持的 bean(可以通过以下方式以编程方式定义此类 bean: 使用 Spring API,尽管您必须查阅源代码 有关如何执行此操作的说明,因为本章不涉及此类高级配置)。 请注意,这是一个迭代步骤。每个动态至少需要一个 Bean 定义 语言源文件(尽管多个 Bean 定义可以引用同一个源文件)。
<lang:language/>
前两个步骤(测试和编写动态语言源文件)超出了范围 本章的范围。请参阅语言规范和参考手册 对于您选择的动态语言,并继续开发您的动态语言 源文件。不过,您首先要阅读本章的其余部分,因为 Spring 的动态语言支持确实对内容做了一些(小的)假设 动态语言源文件。
<lang:language/> 元素
上一节列表中的最后一步涉及定义动态语言支持的
Bean 定义,每个 Bean 对应一个定义
想要配置(这与正常的 JavaBean 配置没有什么不同)。然而
而不是指定要成为的类的完全限定类名
由容器实例化和配置后,可以使用该元素来定义动态语言支持的 bean。<lang:language/>
每种受支持的语言都有一个相应的元素:<lang:language/>
-
<lang:groovy/>
(时髦) -
<lang:bsh/>
(豆壳) -
<lang:std/>
(JSR-223,例如使用 JRuby)
可用于配置的确切属性和子元素取决于 Bean 是用哪种语言定义的(特定于语言的部分 本章后面将对此进行详细说明)。
可提神的豆子
动态语言最引人注目的附加值之一(也许是唯一的) Spring 中的支持是“可刷新的 bean”特性。
可刷新的 Bean 是动态语言支持的 Bean。用少量 配置时,动态语言支持的 Bean 可以监视其底层的更改 源文件资源,然后在动态语言源文件处于 已更改(例如,当您在文件系统上编辑和保存对文件的更改时)。
这样,您就可以将任意数量的动态语言源文件部署为 应用程序,配置 Spring 容器以创建由 dynamic 支持的 bean 语言源文件(使用本章中描述的机制),以及(稍后, 当需求发生变化或其他一些外部因素发挥作用时) 编辑动态 语言源文件,并让它们所做的任何更改都反映在 Bean 中,即 由更改的动态语言源文件提供支持。无需关闭 运行应用程序(如果是 Web 应用程序,则重新部署)。这 动态语言支持的 bean so modified 从 更改了动态语言源文件。
默认情况下,此功能处于关闭状态。 |
现在我们可以看一个例子,看看开始使用
refreshable 是多么容易
豆。要打开可刷新的 bean 功能,您必须只指定一个
Bean 定义元素的附加属性。所以
如果我们坚持前面的例子
本章,以下示例显示了我们将在 Spring XML 中更改的内容
用于实现可刷新 Bean 的配置:<lang:language/>
<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>
这真的是你所要做的。Bean
定义中定义的属性是 Bean 的毫秒数
使用对基础动态语言源文件所做的任何更改进行刷新。
您可以通过为属性分配负值来关闭刷新行为。请记住,默认情况下,刷新行为是
禁用。如果不需要刷新行为,请不要定义属性。refresh-check-delay
messenger
refresh-check-delay
如果我们随后运行以下应用程序,我们可以执行可刷新功能。
(请原谅“跳过箍暂停执行”的恶作剧
在下一段代码中。调用只是为了
当您(在此方案中为开发人员)关闭时,程序的执行暂停
并编辑基础动态语言源文件,以便触发刷新
在动态语言支持的 Bean 上,当程序恢复执行时。System.in.read()
下面的清单显示了此示例应用程序:
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'
如果对脚本的更改发生在
值。对脚本的更改直到实际被拾取
在动态语言支持的 Bean 上调用方法。只有当一个方法
调用动态语言支持的 bean,它检查其底层脚本是否
来源已更改。与刷新脚本相关的任何异常(例如
遇到编译错误或发现脚本文件已被删除)
导致致命异常传播到调用代码。refresh-check-delay
前面描述的可刷新 Bean
行为不适用于动态语言
使用元素表示法定义的源文件(请参阅内联动态语言源文件)。此外,它仅适用于
实际上可以检测到对基础源文件的更改(例如,通过代码
检查存在于
文件系统)。<lang:inline-script/>
内联动态语言源文件
动态语言支持还可以满足以下动态语言源文件的需求:
直接嵌入到 Spring bean 定义中。更具体地说,该元素允许您立即定义动态语言源
在 Spring 配置文件中。一个示例可以阐明内联脚本如何
功能工作:<lang:inline-script/>
<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 配置文件中的动态语言源,该元素在某些情况下可能很有用。例如,我们可能想要快速添加一个
Spring 实现到 Spring MVC 。这只是片刻的
使用内联源工作。(参见 脚本化验证程序 了解此类
示例。<lang:inline-script/>
Validator
Controller
了解动态语言支持的 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
}
<lang:groovy id="badMessenger"
script-source="classpath:Messenger.groovy">
<!-- this next constructor argument will not be injected into the GroovyMessenger -->
<!-- in fact, this isn't even allowed according to the schema -->
<constructor-arg value="This will not work" />
<!-- only property values are injected into the dynamic-language-backed object -->
<lang:property name="anotherMessage" value="Passed straight through to the dynamic-language-backed object" />
</lang>
在实践中,这种限制并不像最初看起来那么重要,因为 setter 注入是绝大多数开发者青睐的注入风格 (我们把关于这是否是一件好事的讨论留到另一天)。
3.2.2. Groovy Beans
本节介绍如何在 Spring 中使用 Groovy 中定义的 bean。
Groovy 主页包含以下描述:
“Groovy 是一种用于 Java 2 平台的敏捷动态语言,它具有许多 人们在 Python、Ruby 和 Smalltalk 等语言中非常喜欢的功能,使 它们可供使用类似 Java 语法的 Java 开发人员使用。
如果你直接从头到尾阅读了本章,你已经看到了一个 Groovy 动态语言支持的示例 豆。现在考虑另一个示例(再次使用 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 中定义的计算器:
<!-- 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 每个源文件一个(公共)类的约定。
使用回调自定义 Groovy 对象
该接口是一个回调,可让您挂钩其他
创建逻辑到创建 Groovy 支持的 bean 的过程中。例如
此接口的实现可以调用任何必需的初始化方法,
设置一些默认属性值,或指定自定义 .以下列表
显示接口定义:GroovyObjectCustomizer
MetaClass
GroovyObjectCustomizer
public interface GroovyObjectCustomizer {
void customize(GroovyObject goo);
}
Spring Framework 实例化
Groovy 支持的 bean 的实例,然后
将创建的传递给指定的(如果一个
已定义)。您可以使用提供的参考执行任何您喜欢的操作。我们预计大多数人都想用它来设置一个习惯
callback,以下示例演示了如何执行此操作: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 命名空间支持,则使用 a 很容易,因为
以下示例显示: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"/>
您也可以指定一个
Groovy(例如 )
甚至是一个完整的 Groovy 对象,与 Spring 的 .此外,您可以设置与自定义的共同点
在级别上配置 bean;
这也导致了共享使用,因此在以下情况下是推荐的
大量脚本化 Bean(避免每个 Bean 有一个独立的实例)。CompilationCustomizer ImportCustomizer CompilerConfiguration GroovyObjectCustomizer GroovyClassLoader ConfigurableApplicationContext.setClassLoader GroovyClassLoader GroovyClassLoader
|
3.2.3. BeanShell Bean
本节介绍如何在 Spring 中使用 BeanShell bean。
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 动态代理,它实现了所有
在元素的属性值中指定的接口(这就是为什么必须在值中提供至少一个接口的原因
属性,因此,在使用 BeanShell 支持的接口时,对接口进行编程
豆)。这意味着对 BeanShell 支持的对象的每个方法调用都会经过
JDK动态代理调用机制。script-interfaces
<lang:bsh>
现在,我们可以展示一个使用基于
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 的 bean。
3.3. 应用场景
在脚本语言中定义 Spring 托管 Bean 的可能场景 有益的是多种多样的。本节介绍两个可能的用例 Spring 中的动态语言支持。
3.3.1. 脚本化的Spring MVC控制器
可以从使用动态语言支持的 Bean 中受益的一组类是 Spring MVC 控制器。在纯 Spring MVC 应用程序中,导航流 通过 Web 应用程序在很大程度上是由封装在 您的 Spring MVC 控制器。作为导航流和其他表示层逻辑 的 Web 应用程序需要更新以响应支持问题或更改 业务需求,通过以下方式实现任何此类所需的更改可能更容易 编辑一个或多个动态语言源文件并查看这些更改 立即反映在正在运行的应用程序的状态中。
请记住,在诸如 春天,你通常的目标是有一个非常薄的展示层,所有 包含在域和服务中的应用程序的丰富业务逻辑 图层类。将 Spring MVC 控制器开发为动态语言支持的 bean 可以 您可以通过编辑和保存文本文件来更改表示层逻辑。任何 对此类动态语言源文件的更改是(取决于配置) 自动反映在动态语言源文件支持的 Bean 中。
实现对动态语言支持的任何更改的自动“拾取” bean,您必须启用“可刷新 bean”功能。请参阅 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())
}
}
<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 可以让你改变 通过编辑和保存简单的文本文件来验证逻辑。任何此类更改都是 (取决于配置)自动反映在执行中 正在运行的应用程序,并且不需要重新启动应用程序。
自动“拾取”对动态语言支持的任何更改 豆子,您必须启用“可刷新豆子”功能。请参阅 Refreshable Beans 以获取此功能的完整和详细处理。 |
以下示例显示了使用 Groovy
动态语言实现的 Spring(有关该接口的讨论,请参阅使用 Spring 的 Validator
接口进行验证):org.springframework.validation.Validator
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。春季AOP 框架实际上并不知道被建议的 Bean 可能是脚本化的 bean,因此您使用(或打算使用)的所有 AOP 用例和功能 使用脚本化 Bean。当您建议脚本化 Bean 时,不能使用基于类的 代理。您必须使用基于接口的代理。
您不仅限于为脚本 Bean 提供建议。你也可以自己写方面 在受支持的动态语言中,并使用此类 Bean 来建议其他 Spring bean。 不过,这确实是动态语言支持的高级使用。
3.4.2. 范围界定
如果不是很明显,脚本化 Bean
的范围可以与
任何其他豆子。各种元素的属性允许
您可以控制底层脚本 Bean 的作用域,就像它对常规
豆。(默认范围为单例,
就像“普通”豆一样。scope
<lang:language/>
以下示例使用该属性将 Groovy
bean 定义为
原型:scope
<?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>
请参阅 IoC 容器中的 Bean Scopes,了解有关 Spring Framework 中范围支持的完整讨论。
3.4.3. XML
模式lang
Spring XML配置中的元素处理公开的对象
用动态语言(如 Groovy 或 BeanShell)编写为 Spring 容器中的 bean。lang
这些元素(以及动态语言支持)在动态语言支持中得到了全面的介绍。请参阅该部分
了解有关此支持和元素的完整详细信息。lang
要使用架构中的元素,您需要在
Spring XML 配置文件的顶部。以下代码片段中的文本引用
正确的架构,以便命名空间中的标签可供您使用:lang
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>