文章目录
1、综述
在实际环境中实现IoC容器的方式主要分为两大类,一类是依赖查找,依赖查找是通过资源定位,把赌赢的资源查找回来;另一种是依赖注入,而Spring主要使用的是依赖注入(DI)。一般而言,依赖注入可以分为3中方式:
- 构造器注入
- setter注入
- 接口注入
构造器注入和setter注入是主要的方式,而接口注入是从别的地方注入的方式,比如在Web工程中,配置的数据源往往是通过服务器(比如Tomcat)去配置的,这个时候可以用JNDI的形式通过接口将它注入Spring IoC容器中来。下面对它们进行详细讲解。
2、演示项目搭建
该演示项目开发环境为IDEA,Project名为“Spring Demo”。
首先,创建名为“SpringDIWays”的Spring Module,具体过程如下:
通过该种方式即可在IDEA中快速构建Spring开发环境。然后在lib文件夹中补充导入测试及日志jar包如下:
在com.ccff.spring.di.ways.pojo包下创建名为“Student”的POJO类,具体代码如下所示:
package com.ccff.spring.di.ways.pojo;
public class Student {
private String name;
private String sex;
private String studentNo;
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", studentNo='" + studentNo + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
在com.ccff.spring.di.ways.test包下创建名为“StudentTest”的测试类,具体代码如下:
package com.ccff.spring.di.ways.test;
import com.ccff.spring.di.ways.pojo.Student;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StudentTest {
private ApplicationContext context;
@Before
public void getContainer(){
context = new ClassPathXmlApplicationContext("spring-config.xml");
}
}
3、构造器注入
构造器注入依赖于构造方法实现,而构造方法可以是有参数的或者是无参数的。在大部分的情况下,我们都是通过类的构造方法来创建类对象,Spring也可以采用反射的方式,通过构造方法来完成注入,这就是构造器注入的原理。
为了让Spring完成对应的构造注入,我们有必要去描述具体的类、构造方法并设置对应的参数,这样Spring就会通过对应的信息用反射的形式来创建对象。
根据常见的场景,将分为如下几种情况进行测试:
3.1 只有无参构造方法(显式无参构造方法或隐士构造方法)。
初始的Student类中并没有显式地给出构造方法,因此该类具有默认的无参构造方法。在spring-config.xml进行如下配置,实现采用无参构造器注入Student bean。具体配置如下:
<?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="student_noneParam_construction" class="com.ccff.spring.di.ways.pojo.Student">
</bean>
</beans>
在StudentTest测试类中添加名为“TestDIByConstruction”的测试方法,用来测试通过无参构造方法是否注入bean成功,具体代码如下:
package com.ccff.spring.di.ways.test;
import com.ccff.spring.di.ways.pojo.Student;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StudentTest {
private ApplicationContext context;
@Before
public void getContainer(){
context = new ClassPathXmlApplicationContext("spring-config.xml");
}
@Test
public void TestDIByConstruction(){
</