Search code examples
javaspringpropertiesenvironmentautowired

Autowired Environment is null


I have an issue with connecting environment to my Spring project. In this class

@Configuration
@ComponentScan(basePackages = "my.pack.offer.*")
@PropertySource("classpath:OfferService.properties")
public class PropertiesUtil {
    @Autowired
    private Environment environment;



    @Bean
    public String load(String propertyName)
    {
        return environment.getRequiredProperty(propertyName);
    }
}

environment always is null.


Solution

  • Autowiring happens later than load() is called (for some reason).

    A workaround is to implement EnvironmentAware and rely on Spring calling setEnvironment() method:

    @Configuration
    @ComponentScan(basePackages = "my.pack.offer.*")
    @PropertySource("classpath:OfferService.properties")
    public class PropertiesUtil implements EnvironmentAware {
        private Environment environment;
    
        @Override
        public void setEnvironment(final Environment environment) {
            this.environment = environment;
        }
    
        @Bean
        public String load(String propertyName)
        {
            return environment.getRequiredProperty(propertyName);
        }
    }