我正在學習春季,但我不明白我必須填補我的結構......例如,我想要一個隊列表,其中每個球隊都有一個球員列表。Spring簡單示例:在JavaConfig中創建bean的列表?
這是代碼,我有我的TeamApplication:
@SpringBootApplication
public class TeamApplication {
public static void main(String[] args) {
SpringApplication.run(TeamApplication.class, args);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Team team = context.getBean(Team.class);
Player player = context.getBean(Player.class);
}
}
那麼我的AppConfig:
@Configuration
public class AppConfig {
@Bean
public Team team() {
return new Team();
}
@Bean
public Player player() {
return new Player();
}
}
所以球員是:
public class Player {
private static final Logger LOG = LoggerFactory.getLogger(Player.class);
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@PostConstruct
public void init() {
LOG.info("Player PostConstruct");
}
@PreDestroy
public void destroy() {
LOG.info("Player PreDestroy");
}
}
和團隊是:
public class Team {
private static final Logger LOG = LoggerFactory.getLogger(Team.class);
private String name;
private List<Player> listPlayer;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Player> getListPlayer() {
return listPlayer;
}
public void setListPlayer(List<Player> listPlayer) {
this.listPlayer = listPlayer;
}
@PostConstruct
public void init() {
LOG.info("Team PostConstruct");
}
@PreDestroy
public void destroy() {
LOG.info("Team PreDestroy");
}
}
現在: - 我必須填寫那些列表?在PostConstruct?但這種方式我一直同DATAS ......在一個簡單的Java應用程序,我首先創建的球員:
Player p1 = new Player();
p1.setName("A");
p1.setAge(20);
Player p2 = new Player();
p1.setName("B");
p1.setAge(21);
Player p3 = new Player();
p1.setName("C");
p1.setAge(22);
然後創建我的團隊:
List<Person> l1 = new LinkedList<>();
l1.add(p1);
l1.add(p2);
Team t1 = new Team();
t1.setListPlayer(l1);
List<Person> l2 = new LinkedList<>();
l2.add(p3);
Team t2 = new Team();
t1.setListPlayer(l2);
所以......春:
- 我在哪裏可以初始化我的球員(在PostConstruct我將總是得到相同的名字/年齡)?
- 我在哪裏到創建我的列表團隊? TeamApplication中的getBean之後?
親切的問候!
你的意思是你想加載的球隊和球員從DB ?!然後展示他們?! –
是的,在這種情況下,從db加載的團隊和玩家是豆嗎? – Hazlo8