package dao;
public interface TestDIDao {
public void sayHello();
}
package dao;
public class TestDIDaoImpl implements TestDIDao {
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("hello");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!-- - Application context definition for JPetStore's business layer. - Containsbean
references to the transaction manager and to the DAOs in - dataAccessContext-local/jta.xml(see
web.xml's "contextConfigLocation"). -->
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<bean id="myTestDIDao" class="dao.TestDIDaoImpl"></bean>
<!-- 将指定类TestDIDaoImpl配置给Spring,让Spring创建其实例 -->
<bean id="testDIService" class="service.TestDIServiceImpl">
<!-- 使用构造方法注入 -->
<constructor-arg index="0" ref="myTestDIDao" />
<!-- 将myTestDIDao注入到TestDIServiceImpl类的属性testDIDao上 -->
</bean>
</beans>
package service;
public interface TestDIService {
public void sayHello();
}
package service;
import dao.TestDIDao;
public class TestDIServiceImpl implements TestDIService {
private TestDIDao testDIDao;
public TestDIServiceImpl(TestDIDao testDIDao) {
super();
this.testDIDao = testDIDao;
}
// 构造方法,用于实现依赖注入接口对象testDIDao
public void sayHello() {
testDIDao.sayHello();
//调用testDIDao中的sayHello方法
System.out.println("构造方法注入");
}
}
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.TestDIService;
public class TestDI {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext xfc = new ClassPathXmlApplicationContext("applicationContext.xml");
//初始化Spring容器ApplicationContext,加载配置文件
TestDIService ts = (TestDIService) xfc.getBean("testDIService");
//通过容器获取实例,测试构造方法注入
ts.sayHello();
}
}