Skip to content

Latest commit

 

History

History
797 lines (579 loc) · 31.8 KB

kotlin.adoc

File metadata and controls

797 lines (579 loc) · 31.8 KB

Kotlin

Kotlin is a statically typed language that targets the JVM (and other platforms), which allows writing concise and elegant code while providing very good interoperability with existing libraries written in Java.

The Spring Framework provides first-class support for Kotlin that lets developers write Kotlin applications almost as if the Spring Framework were a native Kotlin framework.

The easiest way to learn about Spring and Kotlin is to follow this comprehensive tutorial. Feel free to join the #spring channel of Kotlin Slack or ask a question with spring and kotlin as tags on Stackoverflow if you need support.

Requirements

The Spring Framework supports Kotlin 1.3+ and requires kotlin-stdlib (or one of its variants, such as kotlin-stdlib-jdk8) and kotlin-reflect to be present on the classpath. They are provided by default if you bootstrap a Kotlin project on start.spring.io.

Extensions

Kotlin extensions provide the ability to extend existing classes with additional functionality. The Spring Framework Kotlin APIs use these extensions to add new Kotlin-specific conveniences to existing Spring APIs.

The {doc-root}/spring-framework/docs/{spring-version}/kdoc-api/spring-framework/[Spring Framework KDoc API] lists and documents all available the Kotlin extensions and DSLs.

Note
Keep in mind that Kotlin extensions need to be imported to be used. This means, for example, that the GenericApplicationContext.registerBean Kotlin extension is available only if org.springframework.context.support.registerBean is imported. That said, similar to static imports, an IDE should automatically suggest the import in most cases.

For example, Kotlin reified type parameters provide a workaround for JVM generics type erasure, and the Spring Framework provides some extensions to take advantage of this feature. This allows for a better Kotlin API RestTemplate, for the new WebClient from Spring WebFlux, and for various other APIs.

Note
Other libraries, such as Reactor and Spring Data, also provide Kotlin extensions for their APIs, thus giving a better Kotlin development experience overall.

To retrieve a list of User objects in Java, you would normally write the following:

Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)

With Kotlin and the Spring Framework extensions, you can instead write the following:

val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()

As in Java, users in Kotlin is strongly typed, but Kotlin’s clever type inference allows for shorter syntax.

Null-safety

One of Kotlin’s key features is null-safety, which cleanly deals with null values at compile time rather than bumping into the famous NullPointerException at runtime. This makes applications safer through nullability declarations and expressing “value or no value” semantics without paying the cost of wrappers, such as Optional. (Kotlin allows using functional constructs with nullable values. See this comprehensive guide to Kotlin null-safety.)

Although Java does not let you express null-safety in its type-system, the Spring Framework provides null-safety of the whole Spring Framework API via tooling-friendly annotations declared in the org.springframework.lang package. By default, types from Java APIs used in Kotlin are recognized as platform types, for which null-checks are relaxed. Kotlin support for JSR-305 annotations and Spring nullability annotations provide null-safety for the whole Spring Framework API to Kotlin developers, with the advantage of dealing with null-related issues at compile time.

Note
Libraries such as Reactor or Spring Data provide null-safe APIs to leverage this feature.

You can configure JSR-305 checks by adding the -Xjsr305 compiler flag with the following options: -Xjsr305={strict|warn|ignore}.

For kotlin versions 1.1+, the default behavior is the same as -Xjsr305=warn. The strict value is required to have Spring Framework API null-safety taken into account in Kotlin types inferred from Spring API but should be used with the knowledge that Spring API nullability declaration could evolve even between minor releases and that more checks may be added in the future).

Note
Generic type arguments, varargs, and array elements nullability are not supported yet, but should be in an upcoming release. See this discussion for up-to-date information.

Classes and Interfaces

The Spring Framework supports various Kotlin constructs, such as instantiating Kotlin classes through primary constructors, immutable classes data binding, and function optional parameters with default values.

Kotlin parameter names are recognized through a dedicated KotlinReflectionParameterNameDiscoverer, which allows finding interface method parameter names without requiring the Java 8 -parameters compiler flag to be enabled during compilation.

The Jackson Kotlin module, which is required for serializing or deserializing JSON data, is automatically registered when found in the classpath, and a warning message is logged if Jackson and Kotlin are detected without the Jackson Kotlin module being present.

You can declare configuration classes as top level or nested but not inner, since the later requires a reference to the outer class.

Annotations

The Spring Framework also takes advantage of Kotlin null-safety to determine if a HTTP parameter is required without having to explicitly define the required attribute. That means @RequestParam name: String? is treated as not required and, conversely, @RequestParam name: String is treated as being required. This feature is also supported on the Spring Messaging @Header annotation.

In a similar fashion, Spring bean injection with @Autowired, @Bean, or @Inject uses this information to determine if a bean is required or not.

For example, @Autowired lateinit var thing: Thing implies that a bean of type Thing must be registered in the application context, while @Autowired lateinit var thing: Thing? does not raise an error if such a bean does not exist.

Following the same principle, @Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car) implies that a bean of type Toy must be registered in the application context, while a bean of type Car may or may not exist. The same behavior applies to autowired constructor parameters.

Note
If you use bean validation on classes with properties or a primary constructor parameters, you may need to use annotation use-site targets, such as @field:NotNull or @get:Size(min=5, max=15), as described in this Stack Overflow response.

Bean Definition DSL

Spring Framework 5 introduces a new way to register beans in a functional way by using lambdas as an alternative to XML or Java configuration (@Configuration and @Bean). In a nutshell, it lets you register beans with a lambda that acts as a FactoryBean. This mechanism is very efficient, as it does not require any reflection or CGLIB proxies.

In Java, you can, for example, write the following:

	GenericApplicationContext context = new GenericApplicationContext();
	context.registerBean(Foo.class);
	context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class))
);

In Kotlin, with reified type parameters and GenericApplicationContext Kotlin extensions, you can instead write the following:

val context = GenericApplicationContext().apply {
	registerBean<Foo>()
	registerBean { Bar(it.getBean()) }
}

If the class Bar has a single constructor, you can even just specify the bean class, the constructor parameters will be autowired by type:

val context = GenericApplicationContext().apply {
	registerBean<Foo>()
	registerBean<Bar>()
}

In order to allow a more declarative approach and cleaner syntax, Spring Framework provides a {doc-root}/spring-framework/docs/{spring-version}/kdoc-api/spring-framework/org.springframework.context.support/-bean-definition-dsl/[Kotlin bean definition DSL] It declares an ApplicationContextInitializer through a clean declarative API, which lets you deal with profiles and Environment for customizing how beans are registered. The following example creates a Play profile:

val myBeans = beans {
	bean<Foo>()
	bean<Bar>()
	bean("bazBean") {
		Baz().apply {
			message = "Hello world"
		}
	}
	profile("foobar") {
		bean { FooBar(ref("bazBean")) }
	}
}
Note
This DSL is programmatic, meaning it allows custom registration logic of beans through an if expression, a for loop, or any other Kotlin constructs.

You can then use this beans() function to register beans on the application context, as the following example shows:

val context = GenericApplicationContext().apply {
	myBeans.initialize(this)
	refresh()
}

See spring-kotlin-functional beans declaration for a concrete example.

Note
Spring Boot is based on JavaConfig and does not yet provide specific support for functional bean definition, but you can experimentally use functional bean definitions through Spring Boot’s ApplicationContextInitializer support. See this Stack Overflow answer for more details and up-to-date information.

Web

WebFlux router DSL

Spring Framework comes with a Kotlin router DSL available in 2 flavors:

  • Reactive with {doc-root}/spring-framework/docs/{spring-version}/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/-router-function-dsl/[router { }]

  • Coroutines

These DSL let you use the WebFlux functional API to write clean and idiomatic Kotlin code to build a RouterFunction instance as the following example shows:

val routes: RouterFunction<ServerResponse> = 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/"))
}
Note
This DSL is programmatic, meaning that it allows custom registration logic of beans through an if expression, a for loop, or any other Kotlin constructs. That can be useful when you need to register routes depending on dynamic data (for example, from a database).

See MiXiT project routes for a concrete example.

Coroutines

As of Spring Framework 5.2, Coroutines support is provided via extensions for WebFlux client and server functional API. A dedicated {doc-root}/spring-framework/docs/{spring-version}/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/-co-router-function-dsl/[coRouter { }] router DSL is also available.

Coroutines extensions use await prefix or AndAwait suffix, and most are using similar names to their Reactive counterparts, except exchange in WebClient.RequestHeadersSpec which translates to awaitResponse.

fun routes(userHandler: UserHandler): RouterFunction<ServerResponse> = 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("...").awaitResponse().awaitBody<User>()))

	suspend fun listApi(request: ServerRequest): ServerResponse =
				ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8).bodyAndAwait(
				client.get().uri("...").awaitResponse().awaitBody<User>())
}

Read this blog post about structured concurrency to understand how to run code concurrently with Coroutines.

Kotlin Script Templates

As of version 4.3, Spring Framework provides a ScriptTemplateView to render templates by using script engines. It supports JSR-223. Spring Framework 5 goes even further by extending this feature to WebFlux and supporting i18n and nested templates.

Kotlin provides similar support and allows the rendering of Kotlin-based templates. See this commit for details.

This enables some interesting use cases - such as writing type-safe templates by using kotlinx.html DSL or by a using Kotlin multiline String with interpolation.

This can let you write Kotlin templates with full autocompletion and refactoring support in a supported IDE, as the following example shows:

import io.spring.demo.*

"""
${include("header")}
<h1>${i18n("title")}</h1>
<ul>
${users.joinToLine{ "<li>${i18n("user")} ${it.firstname} ${it.lastname}</li>" }}
</ul>
${include("footer")}
"""
Note
Kotlin Script Templates are not compatible yet with Spring Boot fatjar mechanism, see related KT-21443 and KT-27956 issues.

See the kotlin-script-templating example project for more details.

Spring Projects in Kotlin

This section provides some specific hints and recommendations worth for developing Spring projects in Kotlin.

Final by Default

By default, all classes in Kotlin are final. The open modifier on a class is the opposite of Java’s final: It allows others to inherit from this class. This also applies to member functions, in that they need to be marked as open to be overridden.

While Kotlin’s JVM-friendly design is generally frictionless with Spring, this specific Kotlin feature can prevent the application from starting, if this fact is not taken into consideration. This is because Spring beans (such as @Configuration classes which need to be inherited at runtime for technical reasons) are normally proxied by CGLIB. The workaround was to add an open keyword on each class and member function of Spring beans that are proxied by CGLIB (such as @Configuration classes), which can quickly become painful and is against the Kotlin principle of keeping code concise and predictable.

Fortunately, Kotlin now provides a kotlin-spring plugin (a preconfigured version of the kotlin-allopen plugin) that automatically opens classes and their member functions for types that are annotated or meta-annotated with one of the following annotations:

  • @Component

  • @Async

  • @Transactional

  • @Cacheable

Meta-annotations support means that types annotated with @Configuration, @Controller, @RestController, @Service, or @Repository are automatically opened since these annotations are meta-annotated with @Component.

start.spring.io enables it by default, so, in practice, you can write your Kotlin beans without any additional open keyword, as in Java.

Using Immutable Class Instances for Persistence

In Kotlin, it is convenient and considered to be a best practice to declare read-only properties within the primary constructor, as in the following example:

class Person(val name: String, val age: Int)

You can optionally add the data keyword to make the compiler automatically derive the following members from all properties declared in the primary constructor:

  • equals() and hashCode()

  • toString() of the form "User(name=John, age=42)"

  • componentN() functions that correspond to the properties in their order of declaration

  • copy() function

As the following example shows, this allows for easy changes to individual properties, even if Person properties are read-only:

data class Person(val name: String, val age: Int)

val jack = Person(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)

Common persistence technologies (such as JPA) require a default constructor, preventing this kind of design. Fortunately, there is now a workaround for this “default constructor hell”, since Kotlin provides a kotlin-jpa plugin that generates synthetic no-arg constructor for classes annotated with JPA annotations.

If you need to leverage this kind of mechanism for other persistence technologies, you can configure the kotlin-noarg plugin.

Note
As of the Kay release train, Spring Data supports Kotlin immutable class instances and does not require the kotlin-noarg plugin if the module uses Spring Data object mappings (such as MongoDB, Redis, Cassandra, and others).

Injecting Dependencies

Our recommendation is to try and favor constructor injection with val read-only (and non-nullable when possible) properties, as the following example shows:

@Component
class YourBean(
	private val mongoTemplate: MongoTemplate,
	private val solrClient: SolrClient
)
Note
As of Spring Framework 4.3, classes with a single constructor have their parameters automatically autowired, that’s why there is no need for an explicit @Autowired constructor in the example shown above.

If you really need to use field injection, you can use the lateinit var construct, as the following example shows:

@Component
class YourBean {

	@Autowired
	lateinit var mongoTemplate: MongoTemplate

	@Autowired
	lateinit var solrClient: SolrClient
}

Injecting Configuration Properties

In Java, you can inject configuration properties by using annotations (such as @Value("${property}")). However, in Kotlin, $ is a reserved character that is used for string interpolation.

Therefore, if you wish to use the @Value annotation in Kotlin, you need to escape the $ character by writing @Value("\${property}").

As an alternative, you can customize the properties placeholder prefix by declaring the following configuration beans:

@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
	setPlaceholderPrefix("%{")
}

You can customize existing code (such as Spring Boot actuators or @LocalServerPort) that uses the ${…​} syntax, with configuration beans, as the following example shows:

@Bean
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
	setPlaceholderPrefix("%{")
	setIgnoreUnresolvablePlaceholders(true)
}

@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
Note
If you use Spring Boot, you can use @ConfigurationProperties instead of @Value annotations. However, currently, this only works with lateinit or nullable var properties (we recommended the former), since immutable classes initialized by constructors are not yet supported. See these issues about @ConfigurationProperties binding for immutable POJOs and @ConfigurationProperties binding on interfaces for more details.

Checked Exceptions

Java and Kotlin exception handling are pretty close, with the main difference being that Kotlin treats all exceptions as unchecked exceptions. However, when using proxied objects (for example classes or methods annotated with @Transactional), checked exceptions thrown will be wrapped by default in an UndeclaredThrowableException.

To get the original exception thrown like in Java, methods should be annotated with @Throws to specify explicitly the checked exceptions thrown (for example @Throws(IOException::class)).

Annotation Array Attributes

Kotlin annotations are mostly similar to Java annotations, but array attributes (which are extensively used in Spring) behave differently. As explained in Kotlin documentation you can omit the value attribute name, unlike other attributes, and specify it as a vararg parameter.

To understand what that means, consider @RequestMapping (which is one of the most widely used Spring annotations) as an example. This Java annotation is declared as follows:

public @interface RequestMapping {

	@AliasFor("path")
	String[] value() default {};

	@AliasFor("value")
	String[] path() default {};

	RequestMethod[] method() default {};

	// ...
}

The typical use case for @RequestMapping is to map a handler method to a specific path and method. In Java, you can specify a single value for the annotation array attribute, and it is automatically converted to an array.

That is why one can write @RequestMapping(value = "/toys", method = RequestMethod.GET) or @RequestMapping(path = "/toys", method = RequestMethod.GET).

However, in Kotlin 1.2+, you must write @RequestMapping("/toys", method = [RequestMethod.GET]) or @RequestMapping(path = ["/toys"], method = [RequestMethod.GET]) (square brackets need to be specified with named array attributes).

An alternative for this specific method attribute (the most common one) is to use a shortcut annotation, such as @GetMapping, @PostMapping, and others.

Note
Reminder: If the @RequestMapping method attribute is not specified, all HTTP methods will be matched, not only the GET one.

Testing

This section addresses testing with the combination of Kotlin and Spring Framework. The recommended testing framework is JUnit 5, as well as Mockk for mocking.

Constructor injection

As described in the dedicated section, JUnit 5 allows constructor injection of beans which is pretty useful with Kotlin in order to use val instead of lateinit var.

@SpringJUnitConfig(TestConfig::class)
class OrderServiceIntegrationTests(@Autowired val orderService: OrderService,
                                   @Autowired val customerService: CustomerService) {

    // tests that use the injected OrderService and CustomerService
}

You can also use @Autowired at constructor level to autowire all parameters.

@SpringJUnitConfig(TestConfig::class)
class OrderServiceIntegrationTests @Autowired constructor(
        val orderService: OrderService,
        val customerService: CustomerService) {

    // tests that use the injected OrderService and CustomerService
}

PER_CLASS Lifecycle

Kotlin lets you specify meaningful test function names between backticks (`). As of JUnit 5, Kotlin test classes can use the @TestInstance(TestInstance.Lifecycle.PER_CLASS) annotation to enable a single instantiation of test classes, which allows the use of @BeforeAll and @AfterAll annotations on non-static methods, which is a good fit for Kotlin.

You can also change the default behavior to PER_CLASS thanks to a junit-platform.properties file with a junit.jupiter.testinstance.lifecycle.default = per_class property.

The following example demonstrates @BeforeAll and @AfterAll annotations on non-static methods:

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()
  }
}

Specification-like Tests

You can create specification-like tests with JUnit 5 and Kotlin. The following example shows how to do so:

class SpecificationLikeTests {

  @Nested
  @DisplayName("a calculator")
  inner class Calculator {
     val calculator = SampleCalculator()

     @Test
     fun `should return the result of adding the first number to the second number`() {
        val sum = calculator.sum(2, 4)
        assertEquals(6, sum)
     }

     @Test
     fun `should return the result of subtracting the second number from the first number`() {
        val subtract = calculator.subtract(4, 2)
        assertEquals(2, subtract)
     }
  }
}

WebTestClient Type Inference Issue in Kotlin

Due to a type inference issue, you must use the Kotlin expectBody extension (such as .expectBody<String>().isEqualTo("toys")), since it provides a workaround for the Kotlin issue with the Java API.

See also the related SPR-16057 issue.

Getting Started

The easiest way to learn how to build a Spring application with Kotlin is to follow the dedicated tutorial.

start.spring.io

The easiest way to start a new Spring Framework 5 project in Kotlin is to create a new Spring Boot 2 project on start.spring.io.

Choosing the Web Flavor

Spring Framework now comes with two different web stacks: Spring MVC and Spring WebFlux.

Spring WebFlux is recommended if you want to create applications that will deal with latency, long-lived connections, streaming scenarios or if you want to use the web functional Kotlin DSL.

For other use cases, especially if you are using blocking technologies such as JPA, Spring MVC and its annotation-based programming model is the recommended choice.

Resources

We recommend the following resources for people learning how to build applications with Kotlin and the Spring Framework:

Examples

The following Github projects offer examples that you can learn from and possibly even extend:

Issues

The following list categorizes the pending issues related to Spring and Kotlin support: