Kevin
Kevin

Reputation: 1687

How do I replace DynamicPropertyRegistry as a bean method parameter?

I've got a spring-boot v3.2.5 app that runs successfully using testcontainers. I'm upgrading it to spring-boot v3.4.1.

I create the postgres testcontainer like this. It also sets the property spring.flyway.command that is used later on.

    @Bean
    @RestartScope
    @ServiceConnection
    public PostgreSQLContainer<?> postgresContainer(DynamicPropertyRegistry properties) {
      properties.add("spring.flyway.command", () -> MyFlywayMigrationStrategy.MIGRATE);
      return new PostgreSQLContainer<>(
          DockerImageName.parse(PostgresInitializer.POSTGRES_IMAGE));
    }

When I upgrade to spring-boot 3.4.1, this no longer runs, and I get an error about injecting DynamicPropertyRegistry beans. This is documented in the release notes.

Support for defining dynamic properties by injecting a DynamicPropertyRegistry has been deprecated and attempting to do so will now fail by default. Instead of injecting DynamicPropertyRegistry, implement a separate @Bean method that returns a DynamicPropertyRegistrar. This separate bean method should inject the container from which the properties' values will be sourced. This addresses some container lifecycle issues and ensures that the container from which a property’s value has been sourced will have been started before the property is used.

I've tried following the directions in the release notes and came up with this:

    @Bean
    @DependsOn("postgresContainerRegistrar")
    @RestartScope
    @ServiceConnection
    public PostgreSQLContainer<?> postgresContainer() {
      return new PostgreSQLContainer<>(
          DockerImageName.parse(PostgresInitializer.POSTGRES_IMAGE));
    }
    
    @Bean
    public DynamicPropertyRegistrar postgresContainerRegistrar() {
      return registry -> {
        registry.add("spring.flyway.command", () -> MyFlywayMigrationStrategy.MIGRATE);
      };
    }

The spring.flyway.command value is used later like this:

  @Autowired
  public MyFlywayMigrationStrategy(
      @Value("${spring.flyway.command:validate}") String command,
      ApplicationContext applicationContext) {
    this.command = command;
    this.applicationContext = applicationContext;
  }

But the injected value in MyFlywayMigrationStrategy is not what I set on the DynamicPropertyRegistrar. What am I misunderstanding about DynamicPropertyRegistrar or the release notes?

Upvotes: 0

Views: 148

Answers (0)

Related Questions