public class RunDemo { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Game game = context.getBean("game", Game.class); System.out.println(game.playGame());
Team royals = context.getBean("royals", Team.class); game.setAwayTeam(royals); System.out.println(game.playGame()); ... } }
2.2 Bean Scopes
其实之前对Bean的用法都不正确,但这是最简单的用法。
我们队BaseballGame添加toString()方法:
1 2 3 4
@Override public String toString() { return String.format("Game between %s at %s", awayTeam.getName(), homeTeam.getName()); }
然后修改RunDemo中的调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class RunDemo { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Team royals = context.getBean("royals", Team.class);
Game game1 = context.getBean("game", Game.class); System.out.println(game1);
Game game2 = context.getBean("game", Game.class); game2.setAwayTeam(royals); System.out.println(game2);
System.out.println(game1); } } //输出: //Game between Bostom Red Sox at Chicago Cubs //Game between Kansas City Royals at Chicago Cubs //Game between Kansas City Royals at Chicago Cubs
@Configuration @ComponentScan(basePackages = "lx.spring.core") public class AppConfig { ... @Bean @Scope("prototype") //注意这里给Bean添加了@Scope public Game game() { BaseballGame game = new BaseballGame(teams.get(0), teams.get(1)); game.setDataSource(dataSource); return game; } }
public class BaseballGame implements Game { ... public void startGame() { System.out.println("Start game!"); } public void endGame() { System.out.println("End game!"); } ... }