Spring Boot – Environment @Autowired throws NullPointerException

Though your specific problem is solved, here’s how to get Environment in case Spring’s autowiring happens too late.

The trick is to implement org.springframework.context.EnvironmentAware; Spring then passes environment to setEnvironment() method.
This works since Spring 3.1.

An example:

@Configuration
@PropertySource("classpath:myProperties.properties")
public class MyConfiguration implements EnvironmentAware {

    private Environment environment;

    @Override
    public void setEnvironment(final Environment environment) {
        this.environment = environment;
    }

    public void myMethod() {
        final String myPropertyValue = environment.getProperty("myProperty");
        // ...
    }

}

This is not as elegant as @Autowired or @Value, but it works as workaround in some situations.

Leave a Comment