java - Spring 服务 bean 为空
问题描述
我有一个初始化 CLI 游戏的简单 Spring Boot 应用程序。
导入 com.rpg.game.rpggame.client.RpgGameClient;
@SpringBootApplication
public class RpgGameApplication {
public static void main(String[] args) {
SpringApplication.run(RpgGameApplication.class, args);
RpgGameClient.runGame();
}
}
使用我的runGame()
一些服务(spring beans)。
public class RpgGameClient {
@Autowired
private static GameService gameService;
public static void runGame() {
gameService.createNewGame();
}
}
但是我NullPointerException
在使用我的服务时遇到了问题,因为 Spring 无法成功地将它注入我的RpgGameClient
班级。
我该如何解决?
解决方案
1)RpgGameClient
未被声明为候选bean。所以Spring忽略了它。
您可以通过使用@Component
例如(最简单的方法)注释类或声明@Bean
返回类实例的方法来做到这一点。
2)即使这样,它仍然无法正常工作,因为@Autowired
它不适用于static
字段。Spring 将依赖项注入到 bean 中,而 bean 是类的实例。
我认为那runGame()
也应该是 non static
。为 bean spring 设置所有静态是没有意义的。Spring boot 应用程序类也是如此。
3)构造函数注入应该优先于字段注入。
所以应该更好:
@Component
public class RpgGameClient {
private GameService gameService;
public RpgGameClient(GameService gameService){
this.gameService = gameService;
}
public void runGame() {
gameService.createNewGame();
}
}
并更改 Spring Boot 应用程序类以使用注入依赖项,例如:
@SpringBootApplication
public class RpgGameApplication {
@Autowired
RpgGameClient rpgGameClient;
@PostConstruct
public void postConstruct(){
rpgGameClient.runGame();
}
public static void main(String[] args) {
SpringApplication.run(RpgGameApplication.class, args);
}
}
推荐阅读
- html - 在表格行内使用 AJAX.BeginForm 将
在表外更新 - excel - 如何将多个查找和替换变成更有效的循环
- mongodb - 检测到循环依赖(MongoDB Atlas Index)
- reactjs - 警告:propType 失败:提供给 `Route` Google Map React 的无效道具`component`
- regex - 我的正则表达式代码在网站服务器上不起作用,但在我的本地服务器上正常工作
- sapui5 - SAPUI5 - 更新方法上的网关错误
- jenkins - 来自同一代码存储库的不同租户的 Jenkins Docker 映像构建
- c - 客户端如何知道服务器何时发送消息?
- c# - 如何在具有特定命名空间的 Web Api MVC 中获取特定的 xml 格式
- python - 如何通过 Python 代码检索与我的 Facebook 应用程序关联的所有用户数据?