第一种:XML装配
xml装配有两种方式:
第一种:利用有参构造方法注入
User类:
package com.liu.xml;
import java.util.List;
//xml装配bean的两种方式
public class User {
private String username;
private Integer password;
private List<String> list;
//第一种:利用有差构造方法装配bean
public User(String username, Integer password, List<String> list) {
super();
this.username = username;
this.password = password;
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", list=" + list + "]";
}
}
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-4.3.xsd">
<!-- 有参构造方法注入装配user -->
<bean id = "user2" class = "com.liu.xml.User">
<constructor-arg index = "0" value = "lisi"></constructor-arg>
<constructor-arg index = "1" value = "123456"></constructor-arg>
<constructor-arg>
<!-- 注入list -->
<list>
<value>listvalue1</value>
<value>listvalue1</value>
<value>listvalue1</value>
</list>
</constructor-arg>
</bean>
</beans>
测试类:
package com.liu.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanTest {
public static void main(String[] args) {
//获取配置文件路径
String xmlpath ="com/liu/xml/ApplicationContext.xml";
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlpath);
//输出有参构造方法注入的结果
User user2 = (User) applicationContext.getBean("user2");
System.out.println(user2);
}
}
第二种:利用无参构造方法和setter方法注入
User类:
package com.liu.xml;
import java.util.List;
//xml装配bean的两种方式
public class User {
private String username;
private Integer password;
private List<String> list;
//第二种:无参构造方法和setter方法注入
public