自动装配环境为空 [英] Autowired Environment is null

查看:36
本文介绍了自动装配环境为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

环境始终为空.

推荐答案

自动装配发生在 load() 被调用之后(出于某种原因).

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

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

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

这篇关于自动装配环境为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆