1,bean
package com.songyan.zhangpei; import java.util.ArrayList; import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List; public class User { private String userName; private String password; private ArrayList<String> list; @Override public String toString() { String string="[usernname: "+userName+" password: "+password+" list: "+list+"]"; return string; } public User(){} public User(String username,String password,ArrayList<String> list) { this.userName=username; this.password=password; this.list=list; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ArrayList<String> getList() { return list; } public void setList(ArrayList<String> list) { this.list = list; } }
2, 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="user1" class="com.songyan.zhangpei.User"> <property name="userName" value="zhangsan"></property> <property name="password" value="123"></property> <property name="list"> <list> <value>list1</value> <value>list2</value> <value>list3</value> </list> </property> </bean> <bean id="user2" class="com.songyan.zhangpei.User"> <constructor-arg index="0" value="lisi"></constructor-arg> <constructor-arg index="1" value="12345"></constructor-arg> <constructor-arg index="2" > <list> <value>list1</value> <value>list2</value> <value>list3</value> </list></constructor-arg> </bean> </beans>
3, 测试
package com.songyan.zhangpei;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("com/songyan/zhangpei/beanszp.xml");
User user1=(User)applicationContext.getBean("user1");
User user2=(User)applicationContext.getBean("user2");
System.out.println(user1.toString());
System.out.println(user2.toString());
}
}
4, 运行结果
user1使用的是bean装配的设值注入
user2 使用的是bean的构造器注入