基于XML装配Bean有两种方式:设值注入和构造器注入
运行结果:
User类
package com.itheima.assemble;
import java.util.List;
public class User {
private String userName;
private Integer password;
private List<String> list;
/*
* 使用构造器注入
* 提供带所有参数的构造方法
*/
public User(String userName, Integer password, List<String> list) {
super();
this.userName = userName;
this.password = password;
this.list = list;
}
/*
* 使用设值注入
* 提供默认空参构造方法
* 为所有属性提供setter方法
*/
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(Integer password) {
this.password = password;
}
public void setList(List<String> list) {
this.list = list;
}
public User() {
super();
}
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password + ", list=" + list + "]";
}
}
配置文件beans5.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-4.3.xsd">
<!-- 使用构造注入方式装配User实例 -->
<bean id="user1" class="com.itheima.assemble.User">
<constructor-arg index="0" value="tom" />
<constructor-arg index="1" value="123456" />
<constructor-arg index="2" >
<list>
<value>constructorvalue1</value>
<value>constructorvalue2</value>
</list>
</constructor-arg>
</bean>
<!-- 使用setter方式装配User实例 -->
<bean id="user2" class="com.itheima.assemble.User">
<property name="userName" value="张三"></property>
<property name="password" value="111111"></property>
<property name="list">
<list>
<value>"setlistvalue1"</value>
<value>"setlistvalue2"</value>
</list>
</property>
</bean>
</beans>
测试类
package com.itheima.assemble;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
public static void main(String[] args) {
// 定义配置文件的路径
String xmlPath = "com/itheima/assemble/beans5.xml";
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext(xmlPath);
//构造器方式输出
System.out.println(applicationContext.getBean("user1"));
//设值方式输出
System.out.println(applicationContext.getBean("user2"));
}
}