Autowired Environment is null

后端 未结 4 1630
滥情空心
滥情空心 2020-11-28 08:42

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

@Configuration
@ComponentScan(basePackages = \"my.pack.offer.*\")
@PropertyS         


        
4条回答
  •  遥遥无期
    2020-11-28 09:06

    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);
        }
    }
    

提交回复
热议问题