我想创建一个名为
GameSessionRunner
的 Spring Boot 组件,它实现 Runnable
接口。在创建过程中,GameSessionRunner
需要一个SudokuGame
的对象,该对象将通过REST API调用动态创建。
创建
SudokuGame
对象后,我希望 Spring 通过将 GameSessionRunner
对象注入其构造函数来创建 SudokuGame
的新实例。
然后,我想创建一个
GameSession
的对象。该对象将保存对 GameSessionRunner
的引用和用于运行 Thread
的 GameSessionRunner
对象。GameSession
对象将根据其GameSessionRepository
保存到gameId
中。这将允许我稍后使用其 GameSession
检索任何 gameId
。
这些是课程:
GameController
:
@RestController
@RequestMapping("game-server")
public class GameController {
@Autowired
private GameService gameService;
@Autowired
private GameSessionService gameSessionService;
@Autowired
private NotificationService notificationService;
@Autowired
private GameSessionRepository gameSessionRepository;
@CrossOrigin(origins = "*")
@PostMapping("/create-game")
public ResponseEntity<SudokuGame> createGame(@RequestBody CreateGameRequest createGameRequest) {
SudokuGame game = gameService.createGame(createGameRequest);
//Here instead of creating object of GameSessionRunner using new keyword,
//I want spring to create it by passing game object.
GameSessionRunner gameSessionRunner = new GameSessionRunner(game);
Thread gameThread = new Thread(gameSessionRunner);
GameSession gameSession = new GameSession(gameSessionRunner, gameThread);
gameSessionRepository.addGameSession(game.getGameId(), gameSession);
return new ResponseEntity<>(game , HttpStatus.CREATED);
}
}
GameSessionRunner
:
public class GameSessionRunner implements Runnable {
private SudokuGame game;
private boolean isStopped;
private boolean isPaused;
@Autowired
private NotificationService notificationService;
public GameSessionRunner(SudokuGame game) {
this.game = game;
}
@Override
public void run() {
//run implementation.
}
public void pauseGame() {
}
public void resumeGame() {
}
public void stopGame() {
}
}
GameSession
:
public class GameSession {
private GameSessionRunner gameSessionRunner;
private Thread gameThread;
public GameSession(GameSessionRunner gameSessionRunner, Thread gameThread) {
this.gameSessionRunner = gameSessionRunner;
this.gameThread = gameThread;
}
public GameSessionRunner getGameRunner() {
return gameSessionRunner;
}
public Thread getGameThread() {
return gameThread;
}
}
我想使用@AutowiredNotificationServicenotificationService; GameSessionRunner 里面
为此,您可以考虑将其设为原型组件,例如:
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class GameSessionRunner {
@Autowired NotificationService notificationService;
...
然后通过
ObjectProvider
注入:
@Autowired ObjectProvider<GameSessionRunner> gameSessionRunnerObjectProvider;
然后像这样实例化它:
GameSessionRunner gameSessionRunner = gameSessionRunnerObjectProvider
.getObject(<any additional paramaters>);