领先一步
VMware 提供培训和认证,助您加速进步。
了解更多更新:另请参阅 Spring Fu 实验项目。
自我们最初发布(受到社区热烈欢迎!)的 Spring Framework 5 的官方 Kotlin 支持以来,我们一直在与 Spring WebFlux 的最新改进相结合,继续致力于更强大的 Kotlin 支持。
为了演示这些功能以及它们如何协同工作,我创建了一个新的 spring-kotlin-functional 演示应用程序。这是一个独立的 Spring WebFlux 应用程序,使用 Kotlin 开发,支持 Mustache 模板渲染、JSON REST Web 服务和 Server-Sent Events 流式传输功能。在预计于九月发布的 Spring Framework 5 正式版之前,请随时发送您的反馈和建议。
Spring WebFlux 和 Reactor Netty 支持应用程序的编程引导,因为它们天生就设计为作为嵌入式 Web 服务器运行。这在开发 Spring Boot 应用程序时显然不是必需的,但在微服务架构或其他受限环境中,对于具有自定义引导的紧凑部署单元可能非常有用。
class Application {
private val httpHandler: HttpHandler
private val server: HttpServer
private var nettyContext: BlockingNettyContext? = null
constructor(port: Int = 8080) {
val context = GenericApplicationContext().apply {
beans().initialize(this)
refresh()
}
server = HttpServer.create(port)
httpHandler = WebHttpHandlerBuilder.applicationContext(context).build()
}
fun start() {
nettyContext = server.start(ReactorHttpHandlerAdapter(httpHandler))
}
fun startAndAwait() {
server.startAndAwait(ReactorHttpHandlerAdapter(httpHandler),
{ nettyContext = it })
}
fun stop() {
nettyContext?.shutdown()
}
}
fun main(args: Array<String>) {
Application().startAndAwait()
}
Spring Framework 5 引入了一种使用 lambda 注册 Bean 的新方法。它非常高效,不需要任何反射或 CGLIB 代理(因此对于 Reactive 应用 kotlin-spring 插件不是必需的),并且非常适合 Java 8 或 Kotlin 等语言。您可以在 此处概览 Java 与 Kotlin 语法的区别。
在 spring-kotlin-functional 中,Bean 在 Beans.kt 文件中定义。该 DSL 在概念上通过一个干净的声明式 API 声明一个 Consumer<GenericApplicationContext>,该 API 允许您处理 profiles 和 Environment 来自定义 Bean 的注册方式。该 DSL 还允许通过 if 表达式、for 循环或任何其他 Kotlin 结构进行自定义 Bean 注册逻辑。
beans {
bean<UserHandler>()
bean<Routes>()
bean<WebHandler>("webHandler") {
RouterFunctions.toWebHandler(
ref<Routes>().router(),
HandlerStrategies.builder().viewResolver(ref()).build()
)
}
bean("messageSource") {
ReloadableResourceBundleMessageSource().apply {
setBasename("messages")
setDefaultEncoding("UTF-8")
}
}
bean {
val prefix = "classpath:/templates/"
val suffix = ".mustache"
val loader = MustacheResourceTemplateLoader(prefix, suffix)
MustacheViewResolver(Mustache.compiler().withLoader(loader)).apply {
setPrefix(prefix)
setSuffix(suffix)
}
}
profile("foo") {
bean<Foo>()
}
}
在此示例中,bean<Routes>() 使用构造函数自动装配,而 ref<Routes>() 是 applicationContext.getBean(Routes::class.java) 的简写。
Kotlin 的关键特性之一是 空安全,它允许在编译时处理 null 值,而不是在运行时遇到臭名昭著的 NullPointerException。这通过清晰的可空性声明使应用程序更安全,以“有值或无值”的语义,而无需付出类似 Optional 的包装成本。(Kotlin 允许使用函数式结构处理可空值;请查看这个 全面的 Kotlin 空安全指南。)
尽管 Java 不允许在其类型系统中表达空安全,但我们通过对工具友好的注解在 Spring API 中引入了一定程度的空安全:包级别的 @NonNullApi 注解声明非空是默认行为,并且我们明确地将 @Nullable 注解放在特定的参数或返回值可能为 null 的地方。我们已经为整个 Spring Framework API 完成了这项工作(是的,这是一项巨大的努力!),并且像 Spring Data 这样的其他项目也开始利用它。Spring 注解被 JSR 305 元注解(一个不活跃的 JSR,但被 IDEA、Eclipse、Findbugs 等工具支持)元注解,以向 Java 开发人员提供有用的警告。
在 Kotlin 方面,杀手级特性是——自 Kotlin 1.1.51 发布以来——这些注解 被 Kotlin 识别,以便为整个 Spring API 提供空安全。这意味着当您使用 Spring 5 和 Kotlin 时,您的代码中不应该有 NullPointerException,因为编译器不允许这样做。您需要使用 -Xjsr305=strict 编译器标志才能在 Kotlin 类型系统中考虑这些注解。
spring-kotlin-functional 使用 WebFlux 函数式 API 和专用的 Kotlin DSL,而不是使用 @RestController 和 @RequestMapping。
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/"))
}
与 Bean DSL 类似,函数式路由 DSL 允许基于自定义逻辑和动态数据进行函数式路由注册(这对于开发 CMS 或电子商务解决方案可能很有用,因为大多数路由取决于通过后台管理界面创建的数据)。
路由通常指向处理程序,这些处理程序负责根据 HTTP 请求创建 HTTP 响应,通过可调用引用。这是 UserHandler,它利用 Spring Framework 5 在 Spring JAR 中直接提供的 Kotlin 扩展,通过 Kotlin reified 类型参数来避免众所周知的类型擦除问题。在 Java 中相同的代码将需要额外的 Class 或 ParameterizedTypeReference 参数。
class UserHandler {
private val users = Flux.just(
User("Foo", "Foo", LocalDate.now().minusDays(1)),
User("Bar", "Bar", LocalDate.now().minusDays(10)),
User("Baz", "Baz", LocalDate.now().minusDays(100)))
private val userStream = Flux
.zip(Flux.interval(ofMillis(100)), users.repeat())
.map { it.t2 }
fun findAll(req: ServerRequest) =
ok().body(users)
fun findAllView(req: ServerRequest) =
ok().render("users", mapOf("users" to users.map { it.toDto() }))
fun stream(req: ServerRequest) =
ok().bodyToServerSentEvents(userStream)
}
请注意,使用 Spring WebFlux 可以轻松创建 Server-Sent Events 端点,以及服务器端模板渲染(在此应用程序中为 Mustache)。
## 使用 WebClient、Reactor Test 和 JUnit 5 进行轻松测试
Kotlin 允许在反引号之间指定有意义的测试函数名称,并且自 JUnit 5.0 RC2 起,Kotlin 测试类可以使用 @TestInstance(TestInstance.Lifecycle.PER_CLASS) 来启用测试类的单例实例化,这允许在非静态方法上使用 @BeforeAll 和 @AfterAll 注解,这非常适合 Kotlin。现在还可以通过带有 junit.jupiter.testinstance.lifecycle.default = per_class 属性的 junit-platform.properties 文件来更改默认行为为 PER_CLASS。
class IntegrationTests {
val application = Application(8181)
val client = WebClient.create("https://:8181")
@BeforeAll
fun beforeAll() {
application.start()
}
@Test
fun `Find all users on JSON REST endpoint`() {
client.get().uri("/api/users")
.accept(APPLICATION_JSON)
.retrieve()
.bodyToFlux<User>()
.test()
.expectNextMatches { it.firstName == "Foo" }
.expectNextMatches { it.firstName == "Bar" }
.expectNextMatches { it.firstName == "Baz" }
.verifyComplete()
}
@Test
fun `Find all users on HTML page`() {
client.get().uri("/users")
.accept(TEXT_HTML)
.retrieve()
.bodyToMono<String>()
.test()
.expectNextMatches { it.contains("Foo") }
.verifyComplete()
}
@Test
fun `Receive a stream of users via Server-Sent-Events`() {
client.get().uri("/api/users")
.accept(TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux<User>()
.test()
.expectNextMatches { it.firstName == "Foo" }
.expectNextMatches { it.firstName == "Bar" }
.expectNextMatches { it.firstName == "Baz" }
.expectNextMatches { it.firstName == "Foo" }
.expectNextMatches { it.firstName == "Bar" }
.expectNextMatches { it.firstName == "Baz" }
.thenCancel()
.verify()
}
@AfterAll
fun afterAll() {
application.stop()
}
}
## 结论
我们期待您对这些新功能的反馈!请注意,八月是我们完善 API 的最后机会,因为 Spring Framework 5.0 的最终候选版本预计将于月底发布。因此,请随时尝试 spring-kotlin-functional,fork 它,添加新功能,如 Spring Data Reactive Fluent API 等。
我们这边正在着手编写文档。
祝您编码愉快 ;-)