Spring框架的依赖注入通常有两种实现方式,一种是使用构造方法注入,另一种是使用属性的setter方法注入,这里是setter方法注入;
目录结构:
1. 创建com.DI 包,并在包中创建TestDIDao 接口,和接口实现类TestDIDaoImpl;
TestDIDao 接口:
package com.DI;
public interface TestDIDao {
public void sayHello();
}
接口实现类TestDIDaoImpl:
package com.DI;
public class TestDIDaoImpl implements TestDIDao {
public void sayHello(){
System.out.println("TestDIDao");
}
}
2. 创建service包,并在包中创建 TestDIService 接口和接口的是实现类 TestDIServiceImpl;
TestDIService 接口:
package com.service;
public interface TestDIService {
public void sayHello();
}
接口的是实现类 TestDIServiceImpl:
在 TestDIServiceImpl 中使用属性的 setter 方法依赖注入 TestDIDao 接口对象;
package com.service;
import com.DI.TestDIDao;
public class TestDIServiceImpl implements TestDIService{
private TestDIDao testDIDao;
//添加testDIDao属性的setter方法,用于实现依赖注入
public void setTestDIDao(TestDIDao testDIDao){
this.testDIDao=testDIDao;
}
public void sayHello() {
//调用testDIDao中的sayHello方法
testDIDao.sayHello();
System.out.println("setter方法注入");
}
}
3. 编写配置文件 applicationContext.xml ;
将 TestDIServiceImpl 类托管给Spring,让Spring 创建其对象,同时调用 TestDIServiceImpl 类的
setter 方法完成依赖注入。
<?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="myTestDIDao" class="com.DI.TestDIDaoImpl"/>
<!-- 使用setter方法注入 -->
<bean id="testDIService" class="com.service.TestDIServiceImpl">
<!-- 调用 TestDIServiceImpl 类的setter 方法将myTestDIDao注入到
TestDIServiceImpl 类的属性 testDIDao上 -->
<property name="testDIDao" ref="myTestDIDao"/>
</bean>
</beans>
4. 创建 test 包,并创建TestDI 测试类;
package com.test;
import com.service.TestDIService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDI {
public static void main(String[] args) {
//初始化Spring容器,加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext ("applicationContext.xml");
//通过容器获取testDIService 实例,测试setter方法注入
TestDIService ts = (TestDIService) applicationContext.getBean("testDIService");
ts.sayHello();
}
}
5. 执行测试类;