1、User类
import java.util.List;
public class User {
private String username;
private Integer password;
private List<String> list;
/**
* 1.使用构造注入
* 2.提供有参构造函数
*
*/
public User(String username,Integer password,List list)
{
super();
this.username=username;
this.password=password;
this.list=list;
}
public User()
{
super();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", list=" + list + "]";
}
}
2、spring配置文件
<?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-4.3.xsd">
<!-- 构造注入 -->
<bean id="user1" class="com.itheima.assemble.User">
<constructor-arg index="0" value="Tom" ></constructor-arg>
<constructor-arg index="1" value="123456"></constructor-arg>
<constructor-arg index="2">
<list>
<value>"你好微信小程序"</value>
<value>""你好软件工程</value>
</list>
</constructor-arg>
</bean>
<!-- 设置注入 -->
<bean id="user2" class="com.itheima.assemble.User">
<property name="Username" value="javaWeb程序开发入门"></property>
<property name="Password" value="345678"></property>
<property name="list">
<list>
<value>"你好C++"</value>
<value>"你好Python"</value>
</list>
</property>
</bean>
</beans>
配置文件中,constructor-arg元素用于定义构造方法的参数,其属性index表示其索引(从0开始),value属性用于设置注入的值,其子元素list来为User类中对应的list集合属性注入值。设值注入方式装配中property元素用于调用Bean实例中的setter方法完成属性赋值,从而完成依赖注入,而其元素list同样是为User类中对应的list集合属性注入值
3、Test类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
public static void main(String[] args) {
//加载配置文件
ApplicationContext app=new ClassPathXmlApplicationContext("beans5.xml");
//构造注入输出
System.out.println(app.getBean("user1"));
//设值注入输出
System.out.println(app.getBean("user2"));
}
}
4、程序执行结果