Ich habe folgende Konfiguration:Umfang Prototyp funktioniert nicht
@Configuration
public class GameConfig {
@Bean(name = "redsox")
public Team getRedSox() {
return new Team("RedSox");
}
@Bean(name = "boston")
public Team getBoston() {
return new Team("Boston");
}
@Bean @Scope(value="prototype")
public Game getGame(@Qualifier("boston") Team t1, @Qualifier("redsox") Team t2) {
return new Game(t1, t2);
}
@Bean
GameController gameController(Game g) {
return new GameController(g);
}
}
@RestController
@RequestMapping("game")
public class GameController {
Game game;
public GameController(Game game) {
this.game = game;
}
@RequestMapping(path = "play", method = RequestMethod.GET)
public Team play() {
return game.play();
}
@RequestMapping(path = "setHomeTeam", method = RequestMethod.POST)
public void setHomeTeam(@RequestBody Team t) {
game.setHomeTeam(t);
}
}
public class Game {
private Team homeTeam;
private Team awayTeam;
public Game (Team homeTeam, Team awayTeam){
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
}
public Team play(){
Random randomGenerator = new Random();
// Generate random integers in the range 0..1
int randomInt = randomGenerator.nextInt(2);
if (randomInt == 0)
return this.homeTeam;
else
return this.awayTeam;
}
public void setHomeTeam (Team t){
this.homeTeam = t;
}
public void setAwayTeam (Team t){
this.awayTeam = t;
}
}
@Getter @NoArgsConstructor @AllArgsConstructor
public class Team {
private String name;
}
Ich möchte, dass das Spiel nicht Singletone ist. , aber wenn ich POST-Anfrage http://localhost:8080/game/setHomeTeam und dann rufe ich GET-Anfrage http://localhost:8080/game/play es merkt sich das SetHomeTeam.
Die einzige Lösung, die ich war configure Gamecontroller auf andere Weise gefunden haben:
@Bean
@Scope(value="prototype")
GameController gameController(
@Qualifier("boston") Team t1,
@Qualifier("redsox") Team t2
) {
return new GameController(new Game(t1, t2));
}
aber dies schafft den Controller + Spiel als nicht Singletone. Ich möchte nur das Spiel nicht Singletone haben. Gibt es einen besseren/effizienteren Weg?
ist dies eine Ergänzung zu Ihrer Frage? Wenn ja, füge diese Information zu deiner Frage hinzu und lösche diese Antwort. Wenn es die Antwort auf deine Frage ist, könntest du es als akzeptiert markieren;) –