首页 > 解决方案 > 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班级。

我该如何解决?

标签: javaspringspring-bootautowired

解决方案


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

推荐阅读