首页 > 解决方案 > @Autowired 在 Spring 组件中无法正常工作

问题描述

我有一个非常简单的配置和一个很大的困惑,我需要帮助解决。

我有一个带有注释的 BaseController @RestController。在这个类中,我有一个方法,它返回一个字符串并用@GetMapping. 我正在从中读取属性文件并显示应用程序值。到这里为止,一切正常。以下是我的文件,

@RestController
public class BaseController {

    @Autowired
    Environment env;

    @GetMapping("/hello")
    public String hello() {
        String myAppName = env.getProperty("spring.application.name");
        return "From Controller -> " + myAppName;
    }
}

我的application.properties档案,

server.servlet.context-path=/BootEnv
server.port=8085
spring.application.name=EnvironmentAPITester

我打的时候,

http://localhost:8085/BootEnv/hello

,我得到如下正确的回应,

From Controller -> EnvironmentAPITester

在代码中,环境变量是org.springframework.core.env.Environment

到这里为止一切都很好。

现在我创建了一个@Configuration名为ApplicationConfig. 我也想从该类中读取属性文件并返回值。下面是我所做的更改,

@RestController
public class BaseController {

    @Autowired
    Environment env;

    @GetMapping("/hello")
    public String hello() {
        String myAppName = env.getProperty("spring.application.name");
        return "From Controller -> " + myAppName;
    }

    @GetMapping("/helloConf")
    public String getDetails() {
        ApplicationConfig conf = new ApplicationConfig();
        String fromConfig = conf.details();
        return "From Config -> "+fromConfig;
    }
}

下面的课,

@Configuration
public class ApplicationConfig{

    @Autowired
    Environment env;

    public String details() {
        return env.getProperty("spring.application.name");
    }
}

现在当我击球时,

http://localhost:8085/BootEnv/helloConf

我得到一个空指针异常,因为Environment变量为空并且没有自动配置。如何?为什么?

谷歌搜索后,我找到了一个解决方案,要求我实现EnvironmentAware接口并以Environment这种方式设置变量。所以下面是我必须对我的ApplicationConfig班级做出的改变,

@Configuration
public class ApplicationConfig implements EnvironmentAware{

    @Autowired
    Environment env;

    public String details() {
        return env.getProperty("spring.application.name");
    }

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

在这样做之后,它仍然给了我相同Environment变量值的空指针异常。然后我发现不仅我必须删除@Autowire注释,而且我还需要使该变量static使其工作。所以当我这样做时,

//@Autowired
static Environment env;

它完美地工作。而当我击球时,

http://localhost:8085/BootEnv/helloConf

我得到适当的回应,

From Config -> EnvironmentAPITester

困惑是为什么我需要让它static来填充值?为什么EnvironmentAware实现不能在Environment变量仍然存在时设置变量@Autowired

为什么首先,当类类标记有注释时@Autowired不填充Environment变量?即使我将此类注释更改为or或相同的问题仍然存在,即变量失败。怎么来的?ApplicationConfig@Configuration@Service@Repository@Component@AutowireEnvironment

我知道这是一个很长的帖子。但是对此的任何澄清都非常感谢,因为我很难理解这一点。

提前感谢您的帮助。

标签: springspring-mvcspring-bootconfigurationautowired

解决方案


推荐阅读