理解:原来是程序在控制变量,然后输出相应的值
现在是用户在控制变量,程序员不用去修改代码(不违反开闭原则)
相关代码:
Java实现
dao类
UserDao(定义一个接口)
public interface UserDao {
void getUser();
}
UserDaoImpl(接口实现)
public class UserDaoImpl implements UserDao{
@Override
public void getUser() {
System.out.println("获取用户数据");
}
}
UserMysql(接口实现)
public class UserMysql implements UserDao {
@Override
public void getUser() {
System.out.println("获取Mysql数据");
}
}
UserOracle(接口实现)
public class UserOracle implements UserDao{
@Override
public void getUser() {
System.out.println("获取oracle数据");
}
}
service类
UserService(接口)
public interface UserService {
void getUser();
}
UserServiceImpl(接口实现)
public class UserServiceImpl implements UserService{
private UserDao userDao;
//控制反转,用用户来修改条件,而不用去修改代码本身,动态注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
测试:想set方法方法中传入不同的对象就能获得不同的值
// 测试控制反转
@Test
public void getUser(){
// 获得UserServiceImpl的实例
UserServiceImpl userService = new UserServiceImpl();
// 调用set方法传递条件,减少代码的修改
userService.setUserDao(new UserMysql());
userService.getUser();
}
结果:传入new UserMysql()时
传入 new UserOracle()时
spring实现
在beans.xml配置文件中先注册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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDaoImpl" class="com.dao.UserDaoImpl"/>
<bean id="mysqlImpl" class="com.dao.UserMysql"/>
<bean id="oracleImpl" class="com.dao.UserDaoImpl"/>
<!-- id=“这个bean的唯一标识符,class="想注册的类的路径全限定名"”-->
<bean id="serviceImpl" class="com.service.UserServiceImpl">
<!-- ref 动态注入 等同于:userService.setUserDao(new UserMysql()); -->
<property name="userDao" ref="oracleImpl"/>
</bean>
</beans>
测试
@Test
public void get(){
//读取配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//获得接口实例
UserServiceImpl serviceImpl = context.getBean("serviceImpl",UserServiceImpl.class);
//调用接口中的方法
serviceImpl.getUser();
}