被注入的类必须存在一个无参构造函数(按参数顺序和按参数类型两种方式)
Dao
public class PersonDao {
private Integer age;
private String name;
public PersonDao() {
}
/**
* 如果是按照参数顺序来注入,那么可以在<constructor-arg index="1">中设置index来区分以下两个构造函数
*
* 如果是按参数类型来注入,那么以下两个构造函数谁在前面就执行哪个
*
* 注意:如果参数是int类型,<constructor-arg type="java.lang.Integer">会出异常
*/
public PersonDao(String name,Integer age) {
System.out.println("name,age");
this.age = age;
this.name = name;
}
public PersonDao(Integer age, String name) {
System.out.println("age,name");
this.age = age;
this.name = name;
}
public String toString() {
return "PersonDao [age=" + age + ", name=" + name + "]";
}
}
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-2.5.xsd">
<!-- 构造方法注入之参数顺序注入
<bean id="personDao" class="com.xxc.iocc.construct.dao.PersonDao">
<constructor-arg index="1">
<value>zhang</value>
</constructor-arg>
<constructor-arg index="0">
<value>2</value>
</constructor-arg>
</bean>-->
<!-- 构造方法注入之参数类型注入 -->
<bean id="personDao" class="com.xxc.iocc.construct.dao.PersonDao">
<constructor-arg type="java.lang.String">
<value>zhang</value>
</constructor-arg>
<constructor-arg type="java.lang.Integer">
<value>123</value>
</constructor-arg>
</bean>
</beans>
测试类
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("com/xxc/iocc/construct/applicationContext.xml");
PersonDao personDao = (PersonDao)ac.getBean("personDao");
System.out.println(personDao.toString());
}
}