一、构造器注入
<bean id="p" class="com.gql.entity.Person">
<constructor-arg index="0" type="java.lang.String" value="冬雨"></constructor-arg>
<constructor-arg index="1" type="java.lang.Integer" value="18"></constructor-arg>
</bean>
成功通过构造器注入对象。
-
优势:
在获取bean对象时,注入数据是必须的操作
,否则对象无法创建成功。 -
弊端:
改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供
。
(1)constructor-arg标签
标签的属性 | 说明 |
---|---|
index | 指定要注入的数据,为构造函数中指定索引位置的参数赋值 。(索引位置从0开始) |
type | 指定要注入的数据的数据类型 。(该类型也是构造函数中参数的类型) |
name | 为构造器函数中指定名称的参数赋值 。 |
value | 提供基本类型和String类型的数据。 |
ref | 指定其他的bean类型数据。(指在Spring的IoC核心容器中出现过的bean对象) |
(2)测试依赖注入
package com.gql.di;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.gql.entity.Person;
/**
* 类说明:
* 测试依赖注入
* @guoqianliang1998.
*/
public class Demo {
@Test
public void testConstructor(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Person p = (Person)ac.getBean("p");
System.out.println(p.getName()+","+p.getAge());
}
}
(3)Person实体类
在Person实体类中创建了有两个参数的Person构造函数
。
package com.gql.entity;
import java.util.ArrayList;
import java.util.List;
/**
* 类说明:
* 实体类Person
* @guoqianliang1998.
*/
public class Person {
private String name;
private Integer age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void init() {
System.out.println("初始化对象...");
}
public void destroy() {
System.out.println("销毁对象...");
}
}
(4)XML配置
applicationContext_Di.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="p" class="com.gql.entity.Person">
<constructor-arg index="0" type="java.lang.String" value="冬雨"></constructor-arg>
<constructor-arg index="1" type="java.lang.Integer" value="18"></constructor-arg>
</bean>
</beans>
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.xsd">
<import resource="com/gql/di/applicationContext_Di.xml"/>
</beans>