2、spring注入のArrayList数组对象注入方式
流程:我们新建一个Person借口,Chinese去实现Person借口,然而Person中有属性为ArrayList<Properties>的方法,Properties记录该人的一些属性,此处这样用ArrayList并不一定恰当,只是为了举例子而已:
1.Person.java
package study;
public interface Person {
public void output();
}
2.Properties.java
package study;
public class Properties {
private float height;
private int age;
private String favor;
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFavor() {
return favor;
}
public void setFavor(String favor) {
this.favor = favor;
}
}
3.Chinese.java
package study;
import java.util.ArrayList;
import java.util.List;
public class Chinese implements Person {
private List<Properties> properties = new ArrayList<Properties>();
private String name;
/**
* 构造方法
*/
public Chinese() {
System.out.println("Chinese类的构造函数,实例化...");
}
/**
* name的必须的setter方法
* @ 姓名
*/
public void setName(String name) {
this.name = name;
}
/**
* properties必须的setter方法
* @ 属性
*/
public void setProperties(List<Properties> l) {
this.properties = l;
}
@Override
public void output() {
// TODO Auto-generated method stub
System.out.println("姓名:" + this.name);
for (int i = 0; i < properties.size(); i++) {
System.out.println("身高:" + properties.get(i).getHeight());
System.out.println("年龄:" + properties.get(i).getAge());
System.out.println("爱好:" + properties.get(i).getFavor());
}
}
}
4.配置文件bean2.xml
<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-3.0.xsd">
<bean id="chinese" class="study.Chinese">
<property name="name">
<value>zmp</value>
</property>
<property name="properties">
<list>
<bean class="study.Properties">
<property name="height">
<value>183</value>
</property>
<property name="age">
<value>23</value>
</property>
<property name="favor">
<value>运动,读书,写作</value>
</property>
</bean>
<bean class="study.Properties">
<property name="height">
<value>154.3</value>
</property>
<property name="age">
<value>18</value>
</property>
<property name="favor">
<value>关于装逼的视野</value>
</property>
</bean>
</list>
</property>
</bean>
</beans>
5.测试类TestPerson.java
package study;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestPerson {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean2.xml");
Person p = (Person) ctx.getBean("chinese");
p.output();
}
}
6.运行结果: