Skip to content

Mapped port can only be obtained after the container is started when trying to resolve @ConditionalOnProperty #41664

@MrSinisterX

Description

@MrSinisterX

I have an issue related to #40585 . I am using Spring Boot 3.3.2, which should have the fix, however maybe my scenario is slightly different.

I have a bean which has @ConditionalOnProperty("x") and a test containers configuration which uses dynamic property source to inject the exact same proprty "x". What happens is that the conditional tries to resolve the property before the container is started and cannot access the mapped port.

Container configuration

public interface MockAuthServerContainerConfiguration {
  @Container
  MockAuthServerTestContainer MOCK_AUTH_SERVER_TEST_CONTAINER =
      new MockAuthServerTestContainer().withNetwork(Networks.BRIDGE);

  @DynamicPropertySource
  static void setContainerProperties(DynamicPropertyRegistry registry) {
    registry.add(
        "authentication.url",
        () -> String.format(
                "http://localhost:%d/", MOCK_AUTH_SERVER_TEST_CONTAINER.getFirstMappedPort()));
  }
}

Bean configuration

@Configuration
public class AuthenticationBean{

  @Bean
  @ConditionalOnMissingBean
  @ConditionalOnProperty("authentication.url")
  AuthenticationBean authenticationBean() {
             ...
  }
}

Test usage

@Testcontainers
@ImportTestcontainers({MockAuthServerContainerConfiguration .class})

The behavior is that trying to resolve the property in order to determine bean creation happens before the container is started and the port cannot be retrieved: "Mapped port can only be obtained after the container is started"

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: declinedA suggestion or change that we don't feel we should currently apply

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions