语言
1. Kotlin
Spring 框架为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序几乎就像 Spring Framework 是原生 Kotlin 框架一样。 参考文档的大多数代码示例是 除了 Java 之外,还以 Kotlin 提供。
使用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring Boot 和 其专用的 Kotlin 支持。这个全面的教程将教你如何使用 start.spring.io 使用 Kotlin 构建 Spring Boot 应用程序。
欢迎加入 Kotlin Slack 的 #spring 频道,或通过spring
和kotlin
作为 Stackoverflow 上的标签(如果您需要支持)。
1.1. 要求
Spring 框架支持 Kotlin 1.3+,并且需要kotlin-stdlib
(或其变体之一,例如kotlin-stdlib-jdk8
)
和kotlin-reflect
以出现在 Classpath 中。如果您在 start.spring.io 上引导 Kotlin 项目,则默认提供这些 Cookie。
目前尚不支持 Kotlin 内联类。 |
需要 Jackson Kotlin 模块
,以便使用 Jackson 序列化或反序列化 Kotlin 类的 JSON 数据,因此请确保将com.fasterxml.jackson.module:jackson-module-kotlin 依赖项。
在 Classpath 中找到它时,它会自动注册。 |
1.2. 扩展
Kotlin 扩展提供了 以使用其他功能扩展现有类。Spring 框架 Kotlin API 使用这些扩展为现有 Spring API 添加新的特定于 Kotlin 的便利性。
Spring 框架 KDoc API 列表 并记录了所有可用的 Kotlin 扩展和 DSL。
请记住,需要导入 Kotlin 扩展才能使用。这意味着,
例如,该GenericApplicationContext.registerBean Kotlin 扩展
仅在以下情况下可用org.springframework.context.support.registerBean 已导入。
也就是说,与静态导入类似,在大多数情况下,IDE 应该会自动建议导入。 |
例如,Kotlin 具体化类型参数为 JVM 泛型类型擦除提供了一种解决方法。
Spring Framework 提供了一些扩展来利用此功能。
这允许更好的 Kotlin APIRestTemplate
,对于新的WebClient
从 Spring 开始
WebFlux 和其他各种 API 的 API 的 API 中。
其他库(例如 Reactor 和 Spring Data)也提供 Kotlin 扩展 ,从而提供更好的整体 Kotlin 开发体验。 |
要检索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 一样,users
在 Kotlin 中是强类型的,但 Kotlin 巧妙的类型推断允许
以获得更短的语法。
1.3. 空安全
Kotlin 的主要功能之一是 null 安全、
它干净利落地处理了null
值,而不是碰到著名的NullPointerException
在运行时。这通过可为 null 性使应用程序更安全
声明并表达“值或无值”语义,而无需支付包装器的成本,例如Optional
.
(Kotlin 允许使用具有可为 null 值的函数式结构。请参阅此 Kotlin null 安全综合指南。
尽管 Java 不允许在其类型系统中表达 null 安全,但 Spring 框架
通过在org.springframework.lang
包。
默认情况下,Kotlin 中使用的 Java API 中的类型被识别为平台类型。
对此,放宽了 null 检查。Kotlin 对 JSR-305 注释和 Spring 可为 null 性注释为 Kotlin 开发人员的整个 Spring Framework API 提供了空安全性。
具有处理null
- 编译时与问题相关的问题。
Reactor 或 Spring Data 等库提供了 null 安全的 API 来利用此功能。 |
您可以通过添加-Xjsr305
compiler 标志替换为以下内容
选项:-Xjsr305={strict|warn|ignore}
.
对于 kotlin 版本 1.1+,默认行为与-Xjsr305=warn
.
这strict
value 才能考虑 Spring Framework API 空安全
在 Kotlin 类型中,但应在知道 Spring
API 可为 null 性声明甚至可能在次要版本之间演变,并且可能会进行更多检查
在将来添加。
尚不支持泛型类型参数、varargs 和数组元素可为 null 性。 但应该在即将发布的版本中。有关最新信息,请参阅此讨论。 |
1.4. 类和接口
Spring 框架支持各种 Kotlin 结构,例如实例化 Kotlin 类 通过主构造函数、不可变类、数据绑定和函数可选参数 替换为默认值。
Kotlin 参数名称通过专用的KotlinReflectionParameterNameDiscoverer
,
它允许查找接口方法参数名称,而无需 Java 8-parameters
compiler 标志。
您可以将配置类声明为 top level 或 nested 但不能声明为 inner, 因为后者需要对 outer 类的引用。
1.5. 注解
Spring 框架还利用 Kotlin 空安全性来确定是否需要 HTTP 参数,而无需显式
定义required
属性。这意味着@RequestParam name: String?
接受治疗
不是必需的,反之,@RequestParam name: String
被视为必需。
Spring 消息传递也支持此功能@Header
注解。
以类似的方式,Spring bean 注入@Autowired
,@Bean
或@Inject
使用
此信息用于确定 Bean 是否是必需的。
例如@Autowired lateinit var thing: Thing
意味着 bean
的类型Thing
必须在应用程序上下文中注册,而@Autowired lateinit var thing: Thing?
如果不存在这样的 bean,则不会引发错误。
遵循相同的原则,@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)
意味 着
那个 bean 类型的Toy
必须在应用程序上下文中注册,而
类型Car
可能存在也可能不存在。相同的行为适用于自动装配的构造函数参数。
如果你对具有 properties 或主构造函数的类使用 Bean 验证
参数,则可能需要使用 Comments use-site 目标、
如@field:NotNull 或@get:Size(min=5, max=15) ,如此 Stack Overflow 响应中所述。 |
1.6. Bean 定义 DSL
Spring Framework 支持使用 lambda 以功能方式注册 bean
作为 XML 或 Java 配置 (@Configuration
和@Bean
).简而言之
它允许您使用充当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<Foo>()
registerBean { Bar(it.getBean()) }
}
当类Bar
有一个构造函数,你甚至可以只指定 bean 类
构造函数参数将按类型自动装配:
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean<Bar>()
}
为了实现更具声明性的方法和更简洁的语法, Spring Framework 提供了
一个 Kotlin bean 定义 DSL 它声明了一个ApplicationContextInitializer
通过一个干净的声明式 API,
它允许您处理配置文件和Environment
用于定制
如何注册 bean。
在以下示例中,请注意:
-
类型推断通常允许避免为 bean 引用指定类型,例如
ref("bazBean")
-
可以使用 Kotlin 顶级函数通过可调用引用(如
bean(::myRouter)
在此示例中 -
指定
bean<Bar>()
或bean(::myRouter)
,参数按类型自动装配 -
这
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 的注册逻辑
通过if 表达式、for loop 或任何其他 Kotlin 结构。 |
然后,您可以使用此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. 网页
1.7.1. 路由器 DSL
Spring Framework 附带了一个 Kotlin 路由器 DSL,有 3 种风格可供选择:
-
带路由器的 WebMvc.fn DSL { }
-
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 是编程的,这意味着它允许自定义 bean 的注册逻辑
通过if 表达式、for loop 或任何其他 Kotlin 结构。这可能很有用
当您需要根据动态数据(例如,从数据库)注册路由时。 |
有关具体示例,请参阅 MiXiT 项目。
1.7.2. MockMvc DSL
Kotlin DSL 通过以下方式提供MockMvc
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
它支持 JSR-223 使用脚本引擎渲染模板。
通过杠杆scripting-jsr223
依赖项、it
可以使用此类功能通过 kotlinx.html DSL 或 Kotlin 多行插值来呈现基于 Kotlin 的模板String
.
build.gradle.kts
dependencies {
runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
配置通常通过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 示例 project 了解更多详情。
1.7.4. Kotlin 多平台序列化
从 Spring Framework 5.3 开始,Kotlin 多平台序列化是 在 Spring MVC、Spring WebFlux 和 Spring Messaging (RSocket) 中受支持。内置支持目前仅针对 JSON 格式。
要启用它,请按照这些说明添加相关的依赖项和插件。
使用 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 位于 Classpath 中,则它们都将默认配置,因为
Kotlin 序列化旨在仅序列化带有@Serializable
.
使用 Spring Messaging (RSocket),如果要自动配置,请确保 Jackson、GSON 或 JSONB 都不在 Classpath 中。
如果需要 Jackson,请配置KotlinSerializationJsonMessageConverter
手动地。
1.8. 协程
Kotlin 协程就是 Kotlin
轻量级线程允许以命令式方式编写非阻塞代码。在语言方面,
挂起函数为异步作提供了抽象,而在库端,kotlinx.coroutines 提供了如下函数async { }
和像Flow
.
Spring Framework 在以下范围内为 Coroutines 提供支持:
-
Spring MVC 和 WebFlux 中的暂停函数支持
@Controller
-
WebFlux.fn coRouter { } DSL
-
暂停函数和
Flow
RSocket 中的支持@MessageMapping
带注释的方法
1.8.1. 依赖项
在以下情况下启用协程支持kotlinx-coroutines-core
和kotlinx-coroutines-reactor
dependencies 在 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. Reactive 如何转换为 Coroutines?
对于返回值,从 Reactive API 到 Coroutines 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>
对于输入参数:
-
如果不需要 laziness,
fun handler(mono: Mono<T>)
成为fun handler(value: T)
由于可以调用 suspending 函数来获取 value 参数。 -
如果需要 laziness,
fun handler(mono: Mono<T>)
成为fun handler(supplier: suspend () → T)
或fun handler(supplier: suspend () → T?)
Flow
是Flux
等效于协程世界,适用于热流或冷流、有限流或无限流,主要区别如下:
-
Flow
是基于 push 的,而Flux
是推挽式混合动力 -
背压通过挂起功能实现
-
Flow
只有一个单暂停collect
方法和运算符作为扩展实现 -
借助协程,运算符易于实现
-
扩展允许向
Flow
-
收集作正在挂起函数
-
map
算子支持异步作(无需flatMap
),因为它需要一个 suspending 函数参数
有关更多详细信息,包括如何与协程并发运行代码,请参阅这篇关于使用 Spring、Coroutines 和 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. 事务
协程上的事务通过 Reactive 的编程变体支持 从 Spring Framework 5.2 开始提供的事务 Management。
对于挂起函数,一个TransactionalOperator.executeAndAwait
extension 的 API 中。
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
}
}
对于 KotlinFlow
一个Flow<T>.transactional
extension 的 API 中。
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 项目的具体提示和建议 在 Kotlin 中。
1.9.1. 默认为 Final
默认情况下,Kotlin 中的所有类都是final
.
这open
修饰符与 Java 的final
:它允许其他人从这个继承
类。这也适用于成员函数,因为它们需要标记为open
以覆盖。
虽然 Kotlin 的 JVM 友好设计通常与 Spring 没有摩擦,但这个特定的 Kotlin 功能
如果不考虑这一事实,则可以阻止应用程序启动。这是因为
Spring bean(例如@Configuration
注解类,默认情况下需要在运行时扩展,以便技术
原因)通常由 CGLIB 代理。解决方法是添加open
keyword 和
member 函数,该函数可以
很快就会变得痛苦,并且违背了保持代码简洁和可预测的 Kotlin 原则。
也可以使用 CGLIB 代理来避免配置类的 CGLIB 代理@Configuration(proxyBeanMethods = false) .
看proxyBeanMethods Javadoc了解更多详情。 |
幸运的是,Kotlin 提供了一个kotlin-spring
plugin(的kotlin-allopen
插件),该插件会自动打开类
及其成员函数,适用于使用以下项之一进行批注或元批注的类型
附注:
-
@Component
-
@Async
-
@Transactional
-
@Cacheable
元注释支持意味着使用@Configuration
,@Controller
,@RestController
,@Service
或@Repository
会自动打开,因为这些
注解使用@Component
.
start.spring.io 启用
这kotlin-spring
plugin 的 Plugins 中。因此,在实践中,您可以编写 Kotlin bean
无需任何额外open
关键字,就像在 Java 中一样。
Spring Framework 文档中的 Kotlin 代码示例没有明确指定open 在类及其成员函数上。这些示例是为项目编写的
使用kotlin-allopen 插件,因为这是最常用的设置。 |
1.9.2. 使用不可变类实例进行持久化
在 Kotlin 中,声明只读属性非常方便,并且被认为是一种最佳做法 在 Primary 构造函数中,如以下示例所示:
class Person(val name: String, val age: Int)
您可以选择添加这data
关键词使编译器自动从声明的所有属性中派生出以下成员
在 Primary 构造函数中:
-
equals()
和hashCode()
-
toString()
的形式"User(name=John, age=42)"
-
componentN()
按声明顺序与属性对应的函数 -
copy()
功能
如以下示例所示,这允许轻松更改各个属性,即使Person
properties 是只读的:
data class Person(val name: String, val age: Int)
val jack = Person(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
常见的持久性技术(如 JPA)需要默认构造函数,从而防止这种情况
一种设计。幸运的是,这个 “default constructor hell” 有一个解决方法,
由于 Kotlin 提供了kotlin-jpa
插件,该插件为使用 JPA 注释注释的类生成合成 no-arg 构造函数。
如果需要将这种机制用于其他持久性技术,则可以配置
这kotlin-noarg
插件。
从 Kay 版本系列开始, Spring Data 支持 Kotlin 不可变类实例和
不需要kotlin-noarg plugin (如果模块使用 Spring Data 对象映射)
(例如 MongoDB、Redis、Cassandra 等)。 |
1.9.3. 注入依赖项
我们的建议是尝试使用val
read-only(和
non-nullable when possible) 属性、
如下例所示:
@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 中,是用于字符串插值的保留字符。$
因此,如果您希望使用@Value
注解中,您需要通过编写$
@Value("\${property}")
.
如果你使用 Spring Boot,你可能应该使用@ConfigurationProperties 而不是@Value 附注。 |
或者,您可以通过声明 以下配置 bean:
@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
}
您可以自定义现有代码(例如 Spring Boot 执行器或@LocalServerPort
)
,它使用${…}
语法,如下例所示:
@Bean
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
setPlaceholderPrefix("%{")
setIgnoreUnresolvablePlaceholders(true)
}
@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
1.9.5. 检查的异常
Java 和 Kotlin 异常处理非常接近,主要区别在于 Kotlin 将所有异常视为
unchecked 异常。但是,当使用代理对象(例如类或方法
注解@Transactional
),则默认情况下,抛出的已检查异常将包装在
一UndeclaredThrowableException
.
要像在 Java 中一样引发原始异常,方法应该用@Throws
要显式指定引发的已检查异常(例如@Throws(IOException::class)
).
1.9.6. 注解数组属性
Kotlin 注解与 Java 注解大体相似,但数组属性(即
在 Spring 中广泛使用)的行为不同。如 Kotlin 文档中所述,您可以省略
这value
attribute name 的 intent 名称,并将其指定为vararg
参数。
要理解这意味着什么,请考虑@RequestMapping
(这是最广泛的
使用 Spring 注解)作为示例。此 Java 注释的声明如下:
public @interface RequestMapping {
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
RequestMethod[] method() default {};
// ...
}
的典型用例@RequestMapping
是将处理程序方法映射到特定路径
和方法。在 Java 中,您可以为 annotation 数组属性指定单个值
它会自动转换为数组。
这就是为什么人们可以写@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
attribute(最常见的一个)是 to
使用快捷方式注释,例如@GetMapping
,@PostMapping
等。
如果@RequestMapping method 属性,则所有 HTTP 方法都将
匹配,则不仅GET 方法。 |
1.9.7. 测试
如果您使用的是 Spring Boot,请参阅此相关文档。 |
构造函数注入
如专门部分所述,
JUnit 5 允许 bean 的构造函数注入,这对 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。
您还可以将默认行为更改为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 上的 Boot 2 项目。
1.10.2. 选择 Web 风格
Spring Framework 现在带有两个不同的 Web 堆栈:Spring MVC 和 Spring WebFlux。
如果您想创建将处理延迟的应用程序,建议使用 Spring WebFlux, 长期连接、流式处理方案或想要使用 Web 功能 Kotlin DSL 的 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:带有 Google Cloud Platform 集成的 Spring Boot
2. 阿帕奇 Groovy
Groovy 是一种功能强大的、可选类型的动态语言,具有 static-type 和 static 编译功能。它提供简洁的语法,并与任何 现有的 Java 应用程序。
Spring Framework 提供了一个专用的ApplicationContext
支持基于 Groovy 的
Bean 定义 DSL。有关更多详细信息,请参阅 Groovy Bean 定义 DSL。
对 Groovy 的进一步支持,包括用 Groovy 编写的 bean、可刷新的脚本 bean、 以及更多内容,可在 Dynamic Language Support 中使用。
3. 动态语言支持
Spring 为使用已 通过在 Spring 中使用动态语言(例如 Groovy)来定义。此支持允许 您可以使用支持的动态语言编写任意数量的类,并拥有 Spring 容器透明地实例化、配置和依赖注入生成的 对象。
Spring 的脚本支持主要针对 Groovy 和 BeanShell。超越这些 特别支持的语言,支持 JSR-223 脚本机制 用于与任何支持 JSR-223 的语言提供程序集成(从 Spring 4.2 开始), 例如 JRuby。
您可以找到有关此动态语言支持的完整工作示例 立即在 Scenarios 中有用。
3.1. 第一个例子
本章的大部分内容是描述 细节。在深入研究动态语言支持的所有细节之前, 我们看一个用动态语言定义的 bean 的快速示例。动态 第一个 bean 的语言是 Groovy。(此示例的基础取自 Spring 测试套件。如果您想在任何其他 支持的语言,请查看源代码)。
下一个示例显示了Messenger
接口,Groovy bean 将要访问
实现。请注意,此接口是用纯 Java 定义的。依赖对象
注入了对Messenger
不知道底层的
implementation 是一个 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...
}
}
以下示例实现Messenger
Groovy 中的接口:
// 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
implementation 复制到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>
这bookingService
bean (一个DefaultBookingService
) 现在可以使用其私有messenger
member 变量一样,因为Messenger
注入其中的实例是
一个Messenger
实例。这里没有什么特别的事情 — 只是普通的 Java 和
普通的 Groovy。
希望前面的 XML 代码段是不言自明的,但如果不是,请不要过分担心。 请继续阅读,深入了解上述配置的原因和原因。
3.2. 定义由动态语言支持的 bean
本节准确描述了如何在任何 支持的动态语言。
请注意,本章并不试图解释支持的 动态语言。例如,如果您想使用 Groovy 编写某些类 在您的应用程序中,我们假设您已经了解 Groovy。如果您需要更多详细信息 关于动态语言本身,请参阅 末尾的 更多资源 本章。
3.2.1. 常见概念
使用动态语言支持的 bean 所涉及的步骤如下:
-
为动态语言源代码编写测试(自然)。
-
然后编写动态语言源代码本身。
-
使用适当的
<lang:language/>
元素(您可以通过 使用 Spring API,尽管您必须查阅 有关如何执行此作的说明,因为本章不介绍这种类型的高级配置)。 请注意,这是一个迭代步骤。每个动态至少需要一个 bean 定义 language 源文件(尽管多个 bean 定义可以引用同一个源文件)。
前两个步骤(测试和编写动态语言源文件)超出了范围 本章的范围。请参阅语言规范和参考手册 对于您选择的动态语言,并继续开发您的动态语言 源文件。不过,您首先要阅读本章的其余部分,因为 Spring 的动态语言支持确实对内容做了一些(小的)假设 的动态语言源文件。
<lang:language/> 元素
上一节列表中的最后一步涉及定义动态语言支持的 bean 定义,每个 bean 定义
想要配置(这与普通的 JavaBean 配置没有什么不同)。然而
而不是指定要
实例化和配置,您可以使用<lang:language/>
元素来定义动态语言支持的 Bean。
每种支持的语言都有相应的<lang:language/>
元素:
-
<lang:groovy/>
(时髦的) -
<lang:bsh/>
(BeanShell) -
<lang:std/>
(JSR-223,例如使用 JRuby)
可用于配置的确切属性和子元素取决于 确切地说,是用哪种语言定义 Bean(特定于语言的部分 本章稍后将详细介绍这一点)。
可刷新的 Bean
动态语言最引人注目的附加值之一(也许是唯一的) Spring 中的支持是“可刷新的 bean”功能。
可刷新 Bean 是动态语言支持的 Bean。用少量 configuration 中,动态语言支持的 bean 可以监视其底层 bean 中的更改 source file 资源,然后在动态语言源文件为 已更改(例如,当您在文件系统上编辑并保存对文件的更改时)。
这允许您将任意数量的动态语言源文件部署为 应用程序中,配置 Spring 容器以创建由动态 语言源文件(使用本章中介绍的机制)和(稍后的 随着需求的变化或其他一些外部因素的开始发挥作用)编辑一个动态 language 源文件,并且他们所做的任何更改都会反映在 Bean 中,即 由更改的动态语言源文件提供支持。无需关闭 正在运行的应用程序(如果是 Web 应用程序,则为 redeploy)。这 dynamic-language-supported bean so modified 从 更改了动态语言源文件。
默认情况下,此功能处于关闭状态。 |
现在我们可以看一个示例,看看开始使用 refreshable 是多么容易
豆。要打开可刷新 bean 功能,您必须指定一个
additional 属性<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>
这真的就是你所要做的。这refresh-check-delay
在messenger
Bean 定义是 Bean 达到
刷新对基础动态语言源文件所做的任何更改。
您可以通过为refresh-check-delay
属性。请记住,默认情况下,刷新行为为
禁用。如果不需要刷新行为,请不要定义该属性。
如果我们随后运行以下应用程序,则可以执行可刷新功能。
(请原谅那些 “跳过圈子暂停执行 ”的恶作剧
在下一段代码中。这System.in.read()
call 只是为了让
程序的执行在您(本方案中的开发人员)离开时暂停
并编辑基础动态语言源文件,以便触发刷新
在动态语言支持的 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()
method 的Messenger
必须更改实现,以便消息为
用引号括起来。以下清单显示了您
(开发人员) 应向Messenger.groovy
source 文件时,
程序的执行已暂停:
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()
dynamic-language-backed 上的Messenger
implementation 是'I Can Do The Frug'
(请注意,包含
附加引号)。
如果对脚本的更改发生在
这refresh-check-delay
价值。对脚本的更改实际上直到
在动态语言支持的 Bean 上调用方法。只有当方法
调用了动态语言支持的 Bean,它会检查其底层脚本是否
来源已更改。与刷新脚本相关的任何异常(例如
遇到编译错误或发现脚本文件已被删除)
导致致命异常传播到调用代码。
前面描述的可刷新 bean 行为不适用于动态语言
使用<lang:inline-script/>
元素表示法(请参阅内联动态语言源文件)。此外,它仅适用于
实际上可以检测到对底层源文件的更改(例如,通过代码
检查存在于
文件系统)。
内联动态语言源文件
动态语言支持还可以满足以下动态语言源文件的需求
直接嵌入到 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>
如果我们把围绕定义
dynamic 语言源中,<lang:inline-script/>
元素在某些情况下可能很有用。例如,我们可能希望快速添加
SpringValidator
实现到 Spring MVCController
.这只是片刻的
使用内联源工作。(有关此类
示例。
在动态语言支持的 bean 的上下文中理解构造函数注入
关于 Spring 的动态,有一件非常重要的事情需要注意 语言支持。也就是说,你不能(目前)提供构造函数参数 添加到动态语言支持的 bean 中(因此,构造函数注入不适用于 dynamic-language-backed 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 Bean
本节介绍如何在 Spring 中使用 Groovy 中定义的 bean。
Groovy 主页包括以下描述:
“Groovy 是一种面向 Java 2 平台的敏捷动态语言,它具有许多 人们在 Python、Ruby 和 Smalltalk 等语言中非常喜欢的功能,使得 它们可供 Java 开发人员使用类似 Java 的语法。
如果你直接从顶部阅读了本章,你已经看到了一个 Groovy-dynamic-language-backed 的例子 豆。现在考虑另一个示例(再次使用 Spring 测试套件中的示例):
package org.springframework.scripting;
public interface Calculator {
int add(int x, int y);
}
以下示例实现Calculator
Groovy 中的接口:
// 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
.
(有关更多有趣的示例,请参阅 dynamic language showcase 项目以获取更多
complex 示例,或参阅本章后面的示例场景)。
每个 Groovy 源文件不能定义多个类。虽然这是完美的 legal,这(可以说)是一种糟糕的做法。为了始终如一的 方法,您应该(在 Spring 团队看来)尊重标准的 Java 每个源文件一个 (public) 类的约定。
使用回调自定义 Groovy 对象
这GroovyObjectCustomizer
interface 是一个回调,它允许你钩接额外的
创建逻辑添加到创建 Groovy 支持的 bean 的过程中。例如
此接口的实现可以调用任何所需的初始化方法,
设置一些默认属性值,或指定自定义MetaClass
.以下清单
显示了GroovyObjectCustomizer
接口定义:
public interface GroovyObjectCustomizer {
void customize(GroovyObject goo);
}
Spring Framework 实例化 Groovy 支持的 bean 的实例,然后
传递创建的GroovyObject
到指定的GroovyObjectCustomizer
(如果一个
已定义)。您可以使用随附的GroovyObject
参考。我们预计大多数人都希望设置自定义MetaClass
有了这个
callback 的 Tim 函数,以下示例显示了如何执行此作:
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 参考手册的相关部分,或者执行
在线搜索。很多文章都讨论了这个话题。实际上,利用GroovyObjectCustomizer
如果使用 Spring 命名空间支持,则很容易,因为
以下示例显示:
<!-- 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"/>
您还可以指定 GroovyCompilationCustomizer (例如ImportCustomizer )
甚至是一个完整的 GroovyCompilerConfiguration object 与 Spring 的GroovyObjectCustomizer .此外,您可以设置一个通用的GroovyClassLoader 带自定义
在ConfigurableApplicationContext.setClassLoader 水平;
这也导致了共享GroovyClassLoader 用法,因此推荐在以下情况下使用
大量脚本化 bean(避免使用隔离的GroovyClassLoader instance per bean) 的 Bean 的 instance 的 T |
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 动态代理,该代理实现了所有
在script-interfaces
属性值<lang:bsh>
元素(这就是为什么您必须在值
属性,因此,当您使用 BeanShell 支持的
beans) 的 bean 的 T这意味着对 BeanShell 支持的对象的每个方法调用都会通过
JDK 动态代理调用机制。
现在,我们可以展示一个使用基于 BeanShell 的 bean 的完整工作示例,该 bean 实现
这Messenger
interface 中。我们再次展示
的定义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 “class”(同样,我们在这里非常松散地使用这些术语):
<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,您通常的目标是拥有一个非常薄的表示层,其中包含所有 包含在域和服务中的应用程序的丰富业务逻辑 Layer 类。将 Spring MVC 控制器开发为动态语言支持的 bean 允许 您可以通过编辑和保存文本文件来更改表示图层逻辑。任何 对此类动态语言源文件的更改是 (取决于配置) 自动反映在由动态语言源文件支持的 bean 中。
为了实现对 dynamic-language-backed 的任何更改的自动 “拾取” beans 中,您必须启用 “refreshable beans” 功能。有关此功能的完整处理,请参见 Refreshable Bean。 |
以下示例显示了org.springframework.web.servlet.mvc.Controller
实现
通过使用 Groovy 动态语言:
// 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 可以让您更改 验证逻辑。任何此类更改都是 (取决于配置)自动反映在 正在运行的应用程序,并且不需要重新启动应用程序。
实现对 dynamic-language-backed 的任何更改的自动 “拾取” beans 中,您必须启用 'refreshable beans' 功能。有关此功能的完整和详细处理,请参见 Refreshable Bean。 |
以下示例显示了一个 Springorg.springframework.validation.Validator
通过使用 Groovy 动态语言实现(有关的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 提供建议。你也可以自己编写 aspect 并使用此类 bean 来通知其他 Spring bean。 不过,这确实是动态语言支持的高级使用。
3.4.2. 范围
如果不是很明显,则可以采用与
任何其他 bean。这scope
属性<lang:language/>
元素 let
您可以控制底层脚本化 Bean 的范围,就像使用常规的
豆。(默认范围为单例,
就像 “常规” 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>
3.4.3. 使用lang
XML 架构
这lang
元素处理公开已
用动态语言(例如 Groovy 或 BeanShell)编写为 Spring 容器中的 bean。
动态语言支持中全面介绍了这些元素(以及动态语言支持)。请参阅该部分
有关此支持和lang
元素。
要使用lang
schema 中,您需要在
top 的 Spring XML 配置文件。以下代码段中的文本引用
正确的 schema,以便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>