我正在学习春季,但我不明白我必须填补我的结构......例如,我想要一个队列表,其中每个球队都有一个球员列表。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