Skip to main content

Spring Boot 3.1.0-RC1: Service Connections

Spring Boot 3.1.0-RC1 has been released over the weekend, at Spring Boot 3.1.0-M2: Service Connections we mentioned the introduction of new annotations for handling connections to external services. In this version, there have been some changes.

  1. A new module called spring-boot-testcontainers has been added, which creates beans based on Testcontainers implementations that can be used in our tests and at development time 👀

  2. @ServiceConnection is the only annotation required to be along with @Container and allow Spring Boot to perform bean auto-configuration.

Our test would now look like this:

@Container
@ServiceConnection // (1)
private static final PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>("postgres:12")
        .withCopyFileToContainer(MountableFile.forClasspathResource("schema.sql"), "/docker-entrypoint-initdb.d/schema.sql");
  1. @ServiceConnection maps the Spring Boot properties with the values provided by Testcontainers.

But that’s not all, we can now declare PostgreSQLContainer as @Bean, along with @ServiceConnection, and Spring Boot will take care of the auto-configuration so the application can be executed. To do this, you can create a class with the main method in src/test/java and run it.

public class TestDemoApplication {

    public static void main(String[] args) {
        SpringApplication.from(DemoApplication::main).with(DemoConfiguration.class).run(args);
    }

    @TestConfiguration(proxyBeanMethods = false)
    static class DemoConfiguration {

        @Bean
        @ServiceConnection
        public PostgreSQLContainer<?> redisContainer() {
            PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:12")
                    .withCopyFileToContainer(MountableFile.forClasspathResource("schema.sql"), "/docker-entrypoint-initdb.d/schema.sql");
            return postgres;
        }

        @Bean
        ApplicationRunner runner(JdbcTemplate jdbcTemplate) {
            return args -> {
                jdbcTemplate.queryForList("SELECT name, lastname FROM users")
                        .forEach(System.out::println);
            };
        }

    }

}

For testing purposes, add the following dependency org.springframework.boot:spring-boot-starter-web to your pom.xml or build.gradle. The application will be executed connected to a PostgreSQL database running in a container.

You can now visit Spring Initializr and generate a project with Spring Boot 3.1.0-RC1.

Also, check the official documentation of Service Connections and Testcontainers at Development Time.

By the way, did you know about the existence of the modules provided by Testcontainers? You can check them out at module catalog.