### WebClient example in Kotlin Source: https://docs.spring.io/spring-boot/reference/io/rest-client.html Kotlin version of the WebClient example, using the same pre-configured WebClient.Builder bean and a similar GET request to retrieve a Mono
. ```kotlin import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import reactor.core.publisher.Mono @Service class MyService(webClientBuilder: WebClient.Builder) { private val webClient: WebClient init { webClient = webClientBuilder.baseUrl("https://example.org").build() } fun someRestCall(name: String): Mono
{ return webClient.get().uri("/{name}/details", name) .retrieve().bodyToMono(Details::class.java) } } ``` -------------------------------- ### WebClient example in Java Source: https://docs.spring.io/spring-boot/reference/io/rest-client.html Inject the pre-configured WebClient.Builder bean and create a WebClient with a base URL. Use the WebClient to make a GET request and retrieve a Mono
. ```java import reactor.core.publisher.Mono; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; @Service public class MyService { private final WebClient webClient; public MyService(WebClient.Builder webClientBuilder) { this.webClient = webClientBuilder.baseUrl("https://example.org").build(); } public Mono
someRestCall(String name) { return this.webClient.get().uri("/{name}/details", name).retrieve().bodyToMono(Details.class); } } ``` -------------------------------- ### Property ordering example 2 (Properties) Source: https://docs.spring.io/spring-boot/reference/features/external-config.html Shows the same property ordering example with the import declared after the property. The result is the same as the first example. ```properties my.property=value spring.config.import=my.properties ``` -------------------------------- ### Startup failure message for port 8080 in use Source: https://docs.spring.io/spring-boot/reference/features/spring-application.html Example output shown when a web application fails to start because port 8080 is already in use. The message includes a description and an action to resolve the issue. ```none *************************** APPLICATION FAILED TO START *************************** Description: Embedded servlet container failed to start. Port 8080 was already in use. Action: Identify and stop the process that is listening on port 8080 or configure this application to listen on another port. ``` -------------------------------- ### YAML example with only enabled Source: https://docs.spring.io/spring-boot/reference/features/external-config.html YAML equivalent of the properties example with only my.service.enabled. Demonstrates that when security property is not present, the Security instance is null. ```yaml my: service: enabled: true ``` -------------------------------- ### Remote client startup output Source: https://docs.spring.io/spring-boot/reference/using/devtools.html Example output from running RemoteSpringApplication, showing the Spring Boot banner, version, and startup logs. It indicates the LiveReload server runs on port 35729 and the application started successfully. ```none . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / =========|_|==============|___/===================================/_/_/_/ :: Spring Boot Remote :: (v4.1.1) 2026-08-17T10:51:38.751Z INFO 11457 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication v4.1.1 using Java 25.0.4 with PID 11457 (/Users/myuser/.m2/repository/org/springframework/boot/spring-boot-devtools/4.1.1/spring-boot-devtools-4.1.1.jar started by myuser in /opt/apps/) 2026-08-17T10:51:38.769Z INFO 11457 --- [ main] o.s.b.devtools.RemoteSpringApplication : No active profile set, falling back to 1 default profile: "default" 2026-08-17T10:51:40.221Z INFO 11457 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2026-08-17T10:51:40.337Z INFO 11457 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 3.297 seconds (process running for 4.891) ``` -------------------------------- ### Environment variable content example Source: https://docs.spring.io/spring-boot/reference/features/external-config.html Example content of an environment variable named MY_CONFIGURATION that can be imported using the 'env:' prefix. ```properties my.name=Service1 my.cluster=Cluster1 ``` -------------------------------- ### Default Spring Boot startup output Source: https://docs.spring.io/spring-boot/reference/features/spring-application.html Example of the default startup output when a Spring Boot application starts. It shows the Spring Boot banner, version, and INFO log messages including the user, PID, active profile, Tomcat initialization, and graceful shutdown. ```none . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v4.1.1) 2026-08-17T10:51:43.606Z INFO 11484 --- [ main] o.s.b.d.f.logexample.MyApplication : Starting MyApplication using Java 25.0.4 with PID 11484 (/opt/apps/myapp.jar started by myuser in /opt/apps/) 2026-08-17T10:51:43.627Z INFO 11484 --- [ main] o.s.b.d.f.logexample.MyApplication : No active profile set, falling back to 1 default profile: "default" 2026-08-17T10:51:48.207Z INFO 11484 --- [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http) 2026-08-17T10:51:48.266Z INFO 11484 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2026-08-17T10:51:48.275Z INFO 11484 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/11.0.24] 2026-08-17T10:51:48.445Z INFO 11484 --- [ main] b.w.c.s.WebApplicationContextInitializer : Root WebApplicationContext: initialization completed in 4488 ms 2026-08-17T10:51:50.163Z INFO 11484 --- [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/' 2026-08-17T10:51:50.190Z INFO 11484 --- [ main] o.s.b.d.f.logexample.MyApplication : Started MyApplication in 8.35 seconds (process running for 9.787) 2026-08-17T10:51:50.219Z INFO 11484 --- [ionShutdownHook] o.s.boot.tomcat.GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete 2026-08-17T10:51:50.249Z INFO 11484 --- [tomcat-shutdown] o.s.boot.tomcat.GracefulShutdown : Graceful shutdown complete ``` -------------------------------- ### YAML document with environments Source: https://docs.spring.io/spring-boot/reference/features/external-config.html Example YAML configuration showing hierarchical environments with url and name properties. ```yaml environments: dev: url: "https://dev.example.com" name: "Developer Setup" prod: url: "https://another.example.com" name: "My Cool App" ``` -------------------------------- ### Property ordering example 1 (YAML) Source: https://docs.spring.io/spring-boot/reference/features/external-config.html YAML equivalent of the first property ordering example. The order of import declaration does not matter. ```yaml spring: config: import: "my.properties" my: property: "value" ``` -------------------------------- ### YAML example with security username Source: https://docs.spring.io/spring-boot/reference/features/external-config.html YAML equivalent of the properties example, defining my.service.enabled and my.service.security.username. Demonstrates binding with @DefaultValue("USER") for roles. ```yaml my: service: enabled: true security: username: admin ``` -------------------------------- ### Custom info properties in application.yml Source: https://docs.spring.io/spring-boot/reference/actuator/endpoints.html YAML equivalent of the properties example, setting the same info.app.* properties. ```yaml info: app: encoding: "UTF-8" java: source: "17" target: "17" ``` -------------------------------- ### Expected output from the application Source: https://docs.spring.io/spring-boot/reference/actuator/tracing.html The output displayed in a web browser at localhost:8080 after starting the application. ```none Hello World! ``` -------------------------------- ### RSocketGraphQlClient example in Kotlin Source: https://docs.spring.io/spring-boot/reference/web/spring-graphql.html Kotlin version of the RSocketGraphQlClient example using constructor injection of the builder. ```kotlin @Component class RSocketGraphQlClientExample(private val builder: RSocketGraphQlClient.Builder<*>) { ``` -------------------------------- ### Property ordering example 2 (YAML) Source: https://docs.spring.io/spring-boot/reference/features/external-config.html YAML equivalent of the second property ordering example. The order of import declaration does not matter. ```yaml my: property: "value" spring: config: import: "my.properties" ``` -------------------------------- ### Kotlin @KafkaListener example Source: https://docs.spring.io/spring-boot/reference/messaging/kafka.html Kotlin version of the listener endpoint on the 'someTopic' topic. Uses the same annotation and auto-configuration behavior as the Java example. ```kotlin import org.springframework.kafka.annotation.KafkaListener import org.springframework.stereotype.Component @Component class MyBean { @KafkaListener(topics = ["someTopic"]) fun processMessage(content: String?) { // ... } } ``` -------------------------------- ### Initialize OpenTelemetryAppender for Logback/Log4j (Kotlin) Source: https://docs.spring.io/spring-boot/reference/actuator/loggers.html Kotlin equivalent of the OpenTelemetryAppender initializer. Installs the OpenTelemetry instance into the appender during startup. ```kotlin import io.opentelemetry.api.OpenTelemetry import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender import org.springframework.beans.factory.InitializingBean import org.springframework.stereotype.Component @Component class OpenTelemetryAppenderInitializer( private val openTelemetry: OpenTelemetry ) : InitializingBean { override fun afterPropertiesSet() = OpenTelemetryAppender.install(openTelemetry) } ``` -------------------------------- ### Define ApplicationContextRunner with AutoConfigurations (Kotlin) Source: https://docs.spring.io/spring-boot/reference/features/developing-auto-configuration.html Kotlin version of the base runner setup, using Kotlin class references. ```kotlin val contextRunner = ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MyServiceAutoConfiguration::class.java)) ``` -------------------------------- ### Main application code in Kotlin Source: https://docs.spring.io/spring-boot/reference/actuator/tracing.html The same example application written in Kotlin, with a REST endpoint that logs a message. ```kotlin import org.apache.commons.logging.Log import org.apache.commons.logging.LogFactory import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @SpringBootApplication class MyApplication { private val logger: Log = LogFactory.getLog(MyApplication::class.java) @RequestMapping("/") fun home(): String { logger.info("home() has been called") return "Hello, World!" } } fun main(args: Array) { runApplication(*args) } ``` -------------------------------- ### Kotlin @PulsarReader example Source: https://docs.spring.io/spring-boot/reference/messaging/pulsar.html Kotlin version of the reader endpoint that starts reading from the beginning of 'someTopic'. Uses the same annotation and configuration as the Java example. ```kotlin import org.springframework.pulsar.annotation.PulsarReader import org.springframework.stereotype.Component @Component class MyBean { @PulsarReader(topics = ["someTopic"], startMessageId = "earliest") fun processMessage(content: String?) { // ... } } ``` -------------------------------- ### Create test application launcher with fromApplication (Kotlin) Source: https://docs.spring.io/spring-boot/reference/features/dev-services.html Kotlin equivalent of the test launcher, using fromApplication().run(*args). ```kotlin import org.springframework.boot.fromApplication fun main(args: Array) { fromApplication().run(*args) } ``` -------------------------------- ### Spring MVC @RestController example in Java Source: https://docs.spring.io/spring-boot/reference/web/servlet.html A typical @RestController that serves JSON data, with endpoints for getting a user, getting user customers, and deleting a user. Uses @RequestMapping, @GetMapping, @DeleteMapping, and @PathVariable. ```java import java.util.List; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class MyRestController { private final UserRepository userRepository; private final CustomerRepository customerRepository; public MyRestController(UserRepository userRepository, CustomerRepository customerRepository) { this.userRepository = userRepository; this.customerRepository = customerRepository; } @GetMapping("/{userId}") public User getUser(@PathVariable Long userId) { return this.userRepository.findById(userId).get(); } @GetMapping("/{userId}/customers") public List getUserCustomers(@PathVariable Long userId) { return this.userRepository.findById(userId).map(this.customerRepository::findByUser).get(); } @DeleteMapping("/{userId}") public void deleteUser(@PathVariable Long userId) { this.userRepository.deleteById(userId); } } ``` -------------------------------- ### Configure Let's Encrypt PEM bundle with properties Source: https://docs.spring.io/spring-boot/reference/features/ssl.html Configure a PEM bundle for 'example.com' using Certbot-generated files. Enables reloading and sets the server SSL bundle to 'webserver'. ```properties spring.ssl.bundle.pem.webserver.reload-on-update=true spring.ssl.bundle.pem.webserver.keystore.certificate=file:/etc/letsencrypt/live/example.com/fullchain.pem spring.ssl.bundle.pem.webserver.keystore.private-key=file:/etc/letsencrypt/live/example.com/privkey.pem server.ssl.bundle=webserver ``` -------------------------------- ### Spring MVC @RestController example in Kotlin Source: https://docs.spring.io/spring-boot/reference/web/servlet.html Kotlin version of the typical @RestController that serves JSON data, with endpoints for getting a user, getting user customers, and deleting a user. Uses @RequestMapping, @GetMapping, @DeleteMapping, and @PathVariable. ```kotlin import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/users") class MyRestController(private val userRepository: UserRepository, private val customerRepository: CustomerRepository) { @GetMapping("/{userId}") fun getUser(@PathVariable userId: Long): User { return userRepository.findById(userId).get() } @GetMapping("/{userId}/customers") fun getUserCustomers(@PathVariable userId: Long): List { return userRepository.findById(userId).map(customerRepository::findByUser).get() } @DeleteMapping("/{userId}") fun deleteUser(@PathVariable userId: Long) { userRepository.deleteById(userId) } } ``` -------------------------------- ### Java @PulsarReader example Source: https://docs.spring.io/spring-boot/reference/messaging/pulsar.html Creates a reader endpoint that starts reading messages from the beginning of the 'someTopic' topic. The @PulsarReader annotation relies on a PulsarReaderFactory, which can be customized via spring.pulsar.reader.* properties or ReaderBuilderCustomizer beans. ```java import org.springframework.pulsar.annotation.PulsarReader; import org.springframework.stereotype.Component; @Component public class MyBean { @PulsarReader(topics = "someTopic", startMessageId = "earliest") public void processMessage(String content) { // ... } } ``` -------------------------------- ### Launch application with native image tracing agent Source: https://docs.spring.io/spring-boot/reference/packaging/native-image/advanced-topics.html Use this command to start the application with the GraalVM native image tracing agent attached. The agent writes hint files to the specified config output directory on application shutdown. After exercising the code paths, stop the application with ctrl-c, then copy the generated files into src/main/resources/META-INF/native-image/ for use in the next native image build. ```shell $ java -Dspring.aot.enabled=true \ -agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ \ -jar target/myproject-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Typical RestClient usage with injected builder (Kotlin) Source: https://docs.spring.io/spring-boot/reference/io/rest-client.html Kotlin version of the typical RestClient example. It injects the auto-configured RestClient.Builder, sets a base URL, and performs a GET request returning a Details object. ```kotlin import org.springframework.boot.docs.io.restclient.restclient.ssl.Details import org.springframework.stereotype.Service import org.springframework.web.client.RestClient @Service class MyService(restClientBuilder: RestClient.Builder) { private val restClient: RestClient init { restClient = restClientBuilder.baseUrl("https://example.org").build() } fun someRestCall(name: String): Details { return restClient.get().uri("/{name}/details", name) .retrieve().body(Details::class.java)!! } } ``` -------------------------------- ### Typical Spring Boot project layout Source: https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html Shows a recommended directory structure with the main application class in a root package and sub-packages for domain areas like customer and order. ```none com +- example +- myapplication +- MyApplication.java | +- customer | +- Customer.java | +- CustomerController.java | +- CustomerService.java | +- CustomerRepository.java | +- order +- Order.java +- OrderController.java +- OrderService.java +- OrderRepository.java ``` -------------------------------- ### Configure TCP readiness timeouts (Properties and YAML) Source: https://docs.spring.io/spring-boot/reference/features/dev-services.html Shows how to set connect and read timeouts for the TCP readiness check in both application.properties and application.yaml. ```properties spring.docker.compose.readiness.tcp.connect-timeout=10s spring.docker.compose.readiness.tcp.read-timeout=5s ``` ```yaml spring: docker: compose: readiness: tcp: connect-timeout: 10s read-timeout: 5s ``` -------------------------------- ### Kotlin: Use @Testcontainers and @Container with Neo4jContainer Source: https://docs.spring.io/spring-boot/reference/testing/testcontainers.html Kotlin version of the Testcontainers JUnit extension example. The container is declared in a companion object with @Container and @JvmStatic, and starts before tests run. The container is stopped after the test class completes. ```kotlin import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.neo4j.Neo4jContainer; import org.springframework.boot.test.context.SpringBootTest; @Testcontainers @SpringBootTest class MyIntegrationTests { @Test fun myTest() { ... } companion object { @Container @JvmStatic val neo4j = Neo4jContainer("neo4j:5"); } } ``` -------------------------------- ### Typical Spring Boot main method (Kotlin) Source: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html Kotlin equivalent of the typical main method using runApplication. ```kotlin import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.docs.using.structuringyourcode.locatingthemainclass.MyApplication import org.springframework.boot.runApplication @SpringBootApplication class MyApplication fun main(args: Array) { runApplication(*args) } ``` -------------------------------- ### Kotlin: Define a KStream bean with StreamsBuilder Source: https://docs.spring.io/spring-boot/reference/messaging/kafka.html Kotlin equivalent of the Java example, wiring a StreamsBuilder into a @Bean method to create a KStream that reads from 'ks1In', uppercases values, and writes to 'ks1Out'. Requires @EnableKafkaStreams and the kafka-streams dependency. The stream is started automatically unless spring.kafka.streams.auto-startup is set to false. ```kotlin import org.apache.kafka.common.serialization.Serdes import org.apache.kafka.streams.KeyValue import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.kstream.KStream import org.apache.kafka.streams.kstream.Produced import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.kafka.annotation.EnableKafkaStreams import org.springframework.kafka.support.serializer.JacksonJsonSerde @Configuration(proxyBeanMethods = false) @EnableKafkaStreams class MyKafkaStreamsConfiguration { @Bean fun kStream(streamsBuilder: StreamsBuilder): KStream { val stream = streamsBuilder.stream("ks1In") stream.map(this::uppercaseValue).to("ks1Out", Produced.with(Serdes.Integer(), JacksonJsonSerde())) return stream } private fun uppercaseValue(key: Int, value: String): KeyValue { return KeyValue(key, value.uppercase()) } } ``` -------------------------------- ### Properties example with only enabled Source: https://docs.spring.io/spring-boot/reference/features/external-config.html Properties file defining only my.service.enabled. Used to demonstrate that when security property is not present, the Security instance is null. ```properties my.service.enabled=true ``` -------------------------------- ### Kotlin test setup with @DataElasticsearchTest Source: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html Kotlin equivalent of the Java example. Use this annotation to test Data Elasticsearch applications. It configures an ElasticsearchTemplate, scans for @Document classes, and configures Spring Data Elasticsearch repositories. Regular @Component and @ConfigurationProperties beans are not scanned; use @EnableConfigurationProperties to include them. ```kotlin import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.data.elasticsearch.test.autoconfigure.DataElasticsearchTest @DataElasticsearchTest class MyDataElasticsearchTests(@Autowired val repository: SomeRepository) { // ... } ``` -------------------------------- ### Custom ErrorWebExceptionHandler with AbstractErrorWebExceptionHandler (Java) Source: https://docs.spring.io/spring-boot/reference/web/reactive.html Java example of a custom error handler that extends AbstractErrorWebExceptionHandler. It routes requests that accept XML to a handler that returns an XML response. The constructor requires ErrorAttributes, WebProperties, ApplicationContext, and ServerCodecConfigurer. The handleErrorAsXml method is incomplete in the source, showing only the start of the response builder. ```java import reactor.core.publisher.Mono; import org.springframework.boot.autoconfigure.web.WebProperties; import org.springframework.boot.webflux.autoconfigure.error.AbstractErrorWebExceptionHandler; import org.springframework.boot.webflux.error.ErrorAttributes; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.function.server.ServerResponse.BodyBuilder; @Component public class MyErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { public MyErrorWebExceptionHandler(ErrorAttributes errorAttributes, WebProperties webProperties, ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer) { super(errorAttributes, webProperties.getResources(), applicationContext); setMessageReaders(serverCodecConfigurer.getReaders()); setMessageWriters(serverCodecConfigurer.getWriters()); } @Override protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) { return RouterFunctions.route(this::acceptsXml, this::handleErrorAsXml); } private boolean acceptsXml(ServerRequest request) { return request.headers().accept().contains(MediaType.APPLICATION_XML); } public Mono handleErrorAsXml(ServerRequest request) { BodyBuilder builder = ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR); // ... additional builder calls return builder.build(); } } ``` -------------------------------- ### Kotlin example using TestRestTemplate with @SpringBootTest and @AutoConfigureTestRestTemplate Source: https://docs.spring.io/spring-boot/reference/testing/test-utilities.html Use this snippet to write an integration test that makes HTTP requests to a running server. It injects TestRestTemplate via constructor, sends a GET request to /example, and asserts the response status is OK. The nested @TestConfiguration provides a custom RestTemplateBuilder with 1-second connect and read timeouts. ```kotlin import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment import org.springframework.boot.test.context.TestConfiguration import org.springframework.boot.restclient.RestTemplateBuilder import org.springframework.boot.resttestclient.TestRestTemplate import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate import org.springframework.context.annotation.Bean import org.springframework.http.HttpStatus import java.time.Duration @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureTestRestTemplate class MySpringBootTests(@Autowired val template: TestRestTemplate) { @Test fun testRequest() { val response = template.getForEntity("/example", String::class.java) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) // Other assertions to verify the response } @TestConfiguration(proxyBeanMethods = false) internal class RestTemplateBuilderConfiguration { @Bean fun restTemplateBuilder(): RestTemplateBuilder { return RestTemplateBuilder().connectTimeout(Duration.ofSeconds(1)) .readTimeout(Duration.ofSeconds(1)) } } } ``` -------------------------------- ### Implement HelloWorld gRPC service in Java Source: https://docs.spring.io/spring-boot/reference/io/grpc.html Extends HelloWorldGrpc.HelloWorldImplBase and uses @GrpcService to expose the service. The sayHello method builds a HelloReply and sends it via the response observer. ```java import io.grpc.stub.StreamObserver; import org.springframework.grpc.server.service.GrpcService; @GrpcService public class MyHelloWorldService extends HelloWorldGrpc.HelloWorldImplBase { @Override public void sayHello(HelloRequest request, StreamObserver responseObserver) { String message = "Hello '%s'".formatted(request.getName()); HelloReply reply = HelloReply.newBuilder().setMessage(message).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } ``` -------------------------------- ### Import extensionless file with explicit extension attribute (Properties) Source: https://docs.spring.io/spring-boot/reference/features/external-config.html Shorthand for the previous example, using the 'extension=' attribute explicitly. ```properties spring.config.import=file:/etc/config/myconfig[extension=.yaml] ``` -------------------------------- ### OAuth2 Client Registration with Explicit Provider (YAML) Source: https://docs.spring.io/spring-boot/reference/security/oauth2.html YAML equivalent of the properties example. The 'my-client' registration sets the provider to 'example', while the 'example' registration relies on its ID as the provider. ```yaml spring: security: oauth2: client: registration: my-client: client-id: "abcd" client-secret: "password" provider: "example" example: client-id: "abcd" client-secret: "password" ``` -------------------------------- ### Configure both servers with SSL using different key stores (Properties) Source: https://docs.spring.io/spring-boot/reference/actuator/monitoring.html Use these properties to have both the main server and the management server use SSL but with different key stores. The main server uses main.jks and the management server uses management.jks. ```properties server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:main.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=true management.server.ssl.key-store=classpath:management.jks management.server.ssl.key-password=secret ``` -------------------------------- ### runApplication(*args) basic usage Source: https://docs.spring.io/spring-boot/reference/features/kotlin.html Idiomatic way to run a Spring Boot application in Kotlin. Drop-in replacement for SpringApplication.run(MyApplication::class.java, *args). ```kotlin import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class MyApplication fun main(args: Array) { runApplication(*args) } ``` -------------------------------- ### @DataNeo4jTest example in Kotlin Source: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html Kotlin version of the @DataNeo4jTest example. It uses constructor injection for the repository. ```kotlin import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.data.neo4j.test.autoconfigure.DataNeo4jTest @DataNeo4jTest class MyDataNeo4jTests(@Autowired val repository: SomeRepository) { // ... } ``` -------------------------------- ### @DataMongoTest example in Kotlin Source: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html Kotlin version of the @DataMongoTest example. It uses constructor injection for MongoTemplate. ```kotlin import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.data.mongodb.test.autoconfigure.DataMongoTest import org.springframework.data.mongodb.core.MongoTemplate @DataMongoTest class MyDataMongoDbTests(@Autowired val mongoTemplate: MongoTemplate) { // ... } ``` -------------------------------- ### Configure SSL bundle for Cassandra (Properties) Source: https://docs.spring.io/spring-boot/reference/data/nosql.html Applies custom SSL trust material from an SSL bundle named 'example' to the CqlSession. ```properties spring.cassandra.keyspace-name=mykeyspace spring.cassandra.contact-points=cassandrahost1,cassandrahost2 spring.cassandra.local-datacenter=datacenter1 spring.cassandra.ssl.bundle=example ``` -------------------------------- ### Export Readiness State to File (Java) Source: https://docs.spring.io/spring-boot/reference/features/spring-application.html Listens for AvailabilityChangeEvent and creates or removes a file based on the state. Used for Kubernetes exec probes. ```java import org.springframework.boot.availability.AvailabilityChangeEvent; import org.springframework.boot.availability.ReadinessState; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class MyReadinessStateExporter { @EventListener public void onStateChange(AvailabilityChangeEvent event) { switch (event.getState()) { case ACCEPTING_TRAFFIC -> { // create file /tmp/healthy } case REFUSING_TRAFFIC -> { // remove file /tmp/healthy } } } } ``` -------------------------------- ### Configure Let's Encrypt PEM bundle with YAML Source: https://docs.spring.io/spring-boot/reference/features/ssl.html Configure a PEM bundle for 'example.com' using Certbot-generated files. Enables reloading and sets the server SSL bundle to 'webserver'. ```yaml spring: ssl: bundle: pem: webserver: reload-on-update: true keystore: certificate: "file:/etc/letsencrypt/live/example.com/fullchain.pem" private-key: "file:/etc/letsencrypt/live/example.com/privkey.pem" server: ssl: bundle: "webserver" ``` -------------------------------- ### Show extract options with help command Source: https://docs.spring.io/spring-boot/reference/packaging/efficient.html Run this command to see all possible options for the extract command. ```shell $ java -Djarmode=tools -jar my-app.jar help extract ``` -------------------------------- ### @WebServiceServerTest Kotlin example Source: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html Kotlin version of the @WebServiceServerTest example. It configures a MockWebServiceClient and tests a web service endpoint by sending a request and expecting a response payload. ```kotlin import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.webservices.test.autoconfigure.server.WebServiceServerTest import org.springframework.ws.test.server.MockWebServiceClient import org.springframework.ws.test.server.RequestCreators import org.springframework.ws.test.server.ResponseMatchers import org.springframework.xml.transform.StringSource @WebServiceServerTest(ExampleEndpoint::class) class MyWebServiceServerTests(@Autowired val client: MockWebServiceClient) { @Test fun mockServerCall() { client .sendRequest(RequestCreators.withPayload(StringSource(""))) .andExpect(ResponseMatchers.payload(StringSource("42"))) } } ``` -------------------------------- ### @WebServiceClientTest Kotlin example Source: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html Kotlin version of the @WebServiceClientTest example. It configures a MockWebServiceServer and tests a web service client by expecting a request and responding with a payload, then asserting the response status. ```kotlin import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.webservices.test.autoconfigure.client.WebServiceClientTest import org.springframework.ws.test.client.MockWebServiceServer import org.springframework.ws.test.client.RequestMatchers import org.springframework.ws.test.client.ResponseCreators import org.springframework.xml.transform.StringSource @WebServiceClientTest(SomeWebService::class) class MyWebServiceClientTests( @Autowired val server: MockWebServiceServer, @Autowired val someWebService: SomeWebService) { @Test fun mockServerCall() { server .expect(RequestMatchers.payload(StringSource(""))) .andRespond(ResponseCreators.withPayload(StringSource("200"))) assertThat(this.someWebService.test()).extracting(Response::status).isEqualTo(200) } } ``` -------------------------------- ### Kotlin @RabbitListener example Source: https://docs.spring.io/spring-boot/reference/messaging/amqp.html Kotlin equivalent of the Java @RabbitListener example, using a class with a method annotated to listen to 'someQueue' with the 'myFactory' container factory. The message content is received as a nullable String. ```kotlin import org.springframework.amqp.rabbit.annotation.RabbitListener import org.springframework.stereotype.Component @Component class MyBean { @RabbitListener(queues = ["someQueue"], containerFactory = "myFactory") fun processMessage(content: String?) { // ... } } ``` -------------------------------- ### Main application class with @SpringBootApplication (Kotlin) Source: https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html Kotlin example of the main class using @SpringBootApplication and runApplication. Place it in the root package to enable component scanning and entity scanning. ```kotlin import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class MyApplication fun main(args: Array) { runApplication(*args) } ``` -------------------------------- ### SAML 2.0 Relying Party properties example Source: https://docs.spring.io/spring-boot/reference/security/saml2.html Example properties for configuring two relying party registrations under the spring.security.saml2.relyingparty prefix. Includes signing, decryption, single logout, and asserting party settings. ```properties spring.security.saml2.relyingparty.registration.my-relying-party1.signing.credentials[0].private-key-location=path-to-private-key spring.security.saml2.relyingparty.registration.my-relying-party1.signing.credentials[0].certificate-location=path-to-certificate spring.security.saml2.relyingparty.registration.my-relying-party1.decryption.credentials[0].private-key-location=path-to-private-key spring.security.saml2.relyingparty.registration.my-relying-party1.decryption.credentials[0].certificate-location=path-to-certificate spring.security.saml2.relyingparty.registration.my-relying-party1.singlelogout.url=https://myapp/logout/saml2/slo spring.security.saml2.relyingparty.registration.my-relying-party1.singlelogout.response-url=https://remoteidp2.slo.url spring.security.saml2.relyingparty.registration.my-relying-party1.singlelogout.binding=POST spring.security.saml2.relyingparty.registration.my-relying-party1.assertingparty.verification.credentials[0].certificate-location=path-to-verification-cert spring.security.saml2.relyingparty.registration.my-relying-party1.assertingparty.entity-id=remote-idp-entity-id1 spring.security.saml2.relyingparty.registration.my-relying-party1.assertingparty.sso-url=https://remoteidp1.sso.url spring.security.saml2.relyingparty.registration.my-relying-party2.signing.credentials[0].private-key-location=path-to-private-key spring.security.saml2.relyingparty.registration.my-relying-party2.signing.credentials[0].certificate-location=path-to-certificate spring.security.saml2.relyingparty.registration.my-relying-party2.decryption.credentials[0].private-key-location=path-to-private-key spring.security.saml2.relyingparty.registration.my-relying-party2.decryption.credentials[0].certificate-location=path-to-certificate spring.security.saml2.relyingparty.registration.my-relying-party2.assertingparty.verification.credentials[0].certificate-location=path-to-other-verification-cert spring.security.saml2.relyingparty.registration.my-relying-party2.assertingparty.entity-id=remote-idp-entity-id2 spring.security.saml2.relyingparty.registration.my-relying-party2.assertingparty.sso-url=https://remoteidp2.sso.url spring.security.saml2.relyingparty.registration.my-relying-party2.assertingparty.singlelogout.url=https://remoteidp2.slo.url spring.security.saml2.relyingparty.registration.my-relying-party2.assertingparty.singlelogout.response-url=https://myapp/logout/saml2/slo spring.security.saml2.relyingparty.registration.my-relying-party2.assertingparty.singlelogout.binding=POST ``` -------------------------------- ### Project structure with trigger file Source: https://docs.spring.io/spring-boot/reference/using/devtools.html Example directory structure showing where the trigger file .reloadtrigger should be placed in the classpath (src/main/resources). ```none src +- main +- resources +- .reloadtrigger ``` -------------------------------- ### Start Application with CDS Archive Source: https://docs.spring.io/spring-boot/reference/packaging/aot-cache.html Starts the extracted Spring Boot application using the previously generated CDS archive. The archive file must be used with the extracted form of the application, otherwise it has no effect. ```shell $ java -XX:SharedArchiveFile=application.jsa -jar my-app.jar ``` -------------------------------- ### YAML example for binding maps with bracket notation Source: https://docs.spring.io/spring-boot/reference/features/external-config.html Shows how to define map properties in YAML. Keys with brackets must be quoted to be parsed correctly. The example binds to a Map with keys '/key1', '/key2', and 'key3'. ```yaml my: map: "[/key1]": "value1" "[/key2]": "value2" "/key3": "value3" ``` -------------------------------- ### Export Readiness State to File (Kotlin) Source: https://docs.spring.io/spring-boot/reference/features/spring-application.html Kotlin version of the readiness state exporter, listening for AvailabilityChangeEvent and creating or removing a file based on the state. ```kotlin import org.springframework.boot.availability.AvailabilityChangeEvent import org.springframework.boot.availability.ReadinessState import org.springframework.context.event.EventListener import org.springframework.stereotype.Component @Component class MyReadinessStateExporter { @EventListener fun onStateChange(event: AvailabilityChangeEvent) { when (event.state) { ReadinessState.ACCEPTING_TRAFFIC -> { // create file /tmp/healthy } ReadinessState.REFUSING_TRAFFIC -> { // remove file /tmp/healthy } } } } ```