spring - @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
我打的时候,
,我得到如下正确的回应,
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");
}
}
现在当我击球时,
我得到一个空指针异常,因为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;
它完美地工作。而当我击球时,
我得到适当的回应,
From Config -> EnvironmentAPITester
困惑是为什么我需要让它static
来填充值?为什么EnvironmentAware
实现不能在Environment
变量仍然存在时设置变量@Autowired
?
为什么首先,当类类标记有注释时@Autowired
不填充Environment
变量?即使我将此类注释更改为or或相同的问题仍然存在,即变量失败。怎么来的?ApplicationConfig
@Configuration
@Service
@Repository
@Component
@Autowire
Environment
我知道这是一个很长的帖子。但是对此的任何澄清都非常感谢,因为我很难理解这一点。
提前感谢您的帮助。
解决方案
推荐阅读
- r - 复制数据框中列中的前 x 个字符
- javascript - JQuery在事件开始时应用css函数,在结束时恢复
- javascript - ReactJS Button 没有调用 onClick 事件
- python - 在字符串中查找具有已知字符位置的单词
- c# - .NET 在 Web 应用程序中从何处启动 RabbitMQ 客户端连接
- automapper - 自动映射器是否适用于计算属性?
- php - 如何通过上传 CSV 文件使用 php 更新数据库?
- r - 子集 Data.frame 多个条件
- pandas - 按分隔符拆分 Pandas 列名
- r - 如果某些元素在更高级别已经是 NA,如何提取深度嵌套列表的值?