一. 原理
本文章的项目源码可以查看本博客的“资源”处,已上传到那里了。
1.1 list
项目结构如下:
Book.java
package com.atguigu.spring.bean;
public class Book {
private Integer book_id;
private String title;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Integer getBook_id() {
return book_id;
}
public void setBook_id(Integer book_id) {
this.book_id = book_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Book [book_id=" + book_id + ", title=" + title + "]";
}
}
Person.java
package com.atguigu.spring.bean;
import java.util.List;
public class Person {
private String name;
private List<Book> book;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBook() {
return book;
}
public void setBook(List<Book> book) {
this.book = book;
}
@Override
public String toString() {
return "Person [name=" + name + ", book=" + book + "]";
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.atguigu.spring.bean.Person">
<property name="name" value="老王"></property>
<property name="book">
<!-- 构造一个集合进行值的注入 -->
<list>
<ref bean="book"></ref>
<bean class="com.atguigu.spring.bean.Book">
<property name="book_id" value="1002"></property>
<property name="title" value="<<Java从入门到放弃>>"></property>
</bean>
</list>
</property>
</bean>
<bean id="book" class="com.atguigu.spring.bean.Book">
<property name="book_id" value="1001"></property>
<property name="title" >
<value><![CDATA[<<Thinking in Java>>]]></value>
</property>
</bean>
</beans>
Main.java
package com.atguigu.spring.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = context.getBean("person", Person.class);
System.out.println(person);
}
}