依赖注入:将UserServiceImpl实例中所要依赖的UserDaoImpl实例对象通过Spring容器注入到UserServiceImpl实例中。
创建UserDao接口和UserService接口:
UserDao接口:
package com.tan.ioc;
public interface UserDao {
public void say();
}
UserService接口:
package com.tan.ioc;
public interface UserService {
public void say();
}
创建UserDaoImpl类实现UserDao接口,创建UserServiceImpl类实现UserService接口,在UserServiceImpl中想要调用userDao中的方法,就需要将userDao中的实例注入到UserServiceImpl中:
package com.tan.ioc;
public class UserServiceImpl implements UserService {
// 声明UserDao属性
private UserDao userDao;
// 添加UserDao属性的setter方法,用于实现依赖注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
// 实现的接口中方法
public void say() {
//调用userDao中的say()方法,并执行输出语句
this.userDao.say();
System.out.println("userService say hello World !");
}
}
在Spring容器配置文件中将userDao实例注入到userServiceImpl实例中。
<?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-4.3.xsd">
<!-- 将指定类配置给Spring,让Spring创建其对象的实例 -->
<bean id="userDao" class="com.tan.ioc.UserDaoImpl" />
<!--添加一个id为userService的实例 -->
<bean id="userService" class="com.tan.ioc.UserServiceImpl">
<!-- 将id为userDao的Bean实例注入到userService实例中 -->
<property name="userDao" ref="userDao" />
</bean>
</beans>
创建测试类:
package com.tan.ioc;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDI {
public static void main(String[] args) {
//1.初始化spring容器,加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2.通过容器获取UserService实例
UserService userService =
(UserService) applicationContext.getBean("userService");
//3.调用实例中的say()方法
userService.say();
}
}