Search code examples
spring-bootspring-config

@ConfigurationPropertie not working Spring Boot


Here is my application.properies...

extract.magoo=tony

I am trying to read this in.

@Component
@ConfigurationProperties("extract")
public class ApplicationProperties {
    ...
    String magoo;

    @Autowired
    private Environment env;   

    @PostConstruct
    public void validate() {
         System.out.println("******* magoo=" + magoo);
         System.out.println("**** " + env.getProperty("extract.magoo"));
    }

Will output:

******* magoo=null
**** null
**** tony

So the property magoo on the class is never injected. But I can get the value from the Environment bean. So this means it is reading application.properties.

Note in a Configuration class, I have added the @EnableConfigurationProperties annotation.

@Configuration
@EnableConfigurationProperties(ApplicationProperties.class)
public class ExtractToolConfiguration {
...
}

Thanks


Solution

  • You have to enable @ConfigurationProperties by adding @EnableConfigurationProperties on a @Configuration class. Then

    @ConfigurationProperties(prefix="extract")
    public class ApplicationProperties {
      String magoo;
      public void setMagoo(String magoo){
        this.magoo = magoo;
      }
    }
    

    You also need the setter.