Skip to main content

Spring Boot 3.1.0-M2: Service Connections

On Friday, March 24th, Spring Boot 3.1.0-M2 was released, which adds new annotations with the purpose of reducing the necessary configuration when using Testcontainers, solving the issue spring-projects/spring-boot#34658.

Below is an example of how to use PostgreSQL in our tests:

@Container // (1)
private static final PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>("postgres:12") // (2)
        .withCopyFileToContainer(MountableFile.forClasspathResource("schema.sql"), "/docker-entrypoint-initdb.d/schema.sql"); // (3)
  1. Annotation that, together with @Testcontainers, will handle the container’s lifecycle.

  2. Declaration of the Testcontainers' container implementation, in this case PostgreSQLContainer.

  3. schema.sql file will be copied to the /docker-entrypoint-initdb.d/ path so that it runs when the container starts.

The content of the schema.sql script, located in src/test/resources, is as follows:

CREATE TABLE users (
  id SERIAL,
  username VARCHAR(255) NOT NULL,
  name VARCHAR(255) NOT NULL,
  lastname VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO users (username, name, lastname) VALUES ('eddumelendez', 'Eddú', 'Meléndez');
Tip
It is recommended to use Liquibase or Flyway to handle database migrations.

Before Spring Boot 3.1.0-M2:

Previous to this version, it was necessary to manually map Testcontainers properties.

@DynamicPropertySource
static void postgresqlProperties(DynamicPropertyRegistry registry) { // (1)
    registry.add("spring.datasource.url", postgresContainer::getJdbcUrl);
    registry.add("spring.datasource.username", postgresContainer::getUsername);
    registry.add("spring.datasource.password", postgresContainer::getPassword);
}
  1. Static method that has been used for the corresponding mapping of properties from Testcontainers.

After Spring Boot 3.1.0-M2

Now, using @JdbcServiceConnection, we can declare the Testcontainers' container database implementation and Spring Boot will automatically map the properties.

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

For more information, you can refer to the following link and see what annotations are available.

There are other changes in this version; it will no longer be necessary to declare the testcontainers-bom, and to update the version of Testcontainers, we simply need to update the version that Spring Boot provides as follows.

<testcontainers.version>1.17.6</testcontainers.version>