Search code examples
spring-bootpropertiesspring-boot-starter

application.properties not read with @EnableAutoConfiguration and custom spring boot starter


I try to create a simple custom spring boot starter that read property in application.properties :

@EnableConfigurationProperties({ CustomStarterProperties.class })
@Configuration
public class CustomStarterAutoConfiguration {

    @Autowired
    private CustomStarterProperties properties;

    @Bean
    public String customStarterMessage() {
        return properties.getMessage();
    }
}

with its ConfigurationProperties :

@ConfigurationProperties(prefix = "custom.starter")
public class CustomStarterProperties {

    private String message;

  /* getter and setter */
           ...
}

There is also the corresponding application.properties and META-INF/spring.factories to enable the autoconfiguration.

I have another project that declares this starter as a dependency and in which I write a test to see if the customStarterMessage Bean is created :

@RunWith(SpringRunner.class)
@EnableAutoConfiguration
public class TotoTest {

    @Autowired
    String customStarterMessage;

    @Test
    public void loadContext() {
        assertThat(customStarterMessage).isNotNull();
    }
}

This test fails (even with the appropriate application.properties file in the project) because the application.properties seems to not be read.

It works well with a @SpringBootTest annotation instead of the @EnableAutoConfiguration but I would like to understand why EnableAutoConfiguration is not using my application.properties file whereas from my understanding all the Spring AutoConfiguration are based on properties.

Thanks


Solution

  • @EnableAutoConfiguration on test classes don't prepare required test context for you.

    Whereas @SpringBootTest does default test context setup for you based on default specification like scanning from root package, loading from default resources. To load from custom packages which are not part of root package hierarchy, loading from custom resource directories you have define that even in test context configuration. All your configurations will be automatically done in your actual starter project based on @EnableAutoConfiguration you defined.