当前位置: 首页 > 面试题库 >

Autowired Environment is null

强宾白
2023-03-14
问题内容

我在将环境连接到Spring项目时遇到问题。在这个班上

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

环境始终为null。


问题答案:

自动装配发生的时间比load()所谓的晚(由于某种原因)。

一种解决方法是实现EnvironmentAware并依赖Spring调用setEnvironment()方法:

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


 类似资料:

相关阅读

相关文章

相关问答