11.1 依赖注入(DI)与控制反转(IOC)的基本概念
在MVC架构中,dao层负责单一的数据库操作,service负责调用多个dao方法进行事务处理。这就导致service层需要使用dao实例对象,同理,controller层需要使用service的方法来进行具体请求的处理。故而上层需要依赖下层的具体的实例对象,即service依赖dao,而controller依赖service。如果我们需要改进下层的方法,而上层的代码中已经写死需要依赖哪个具体的实例对象,则我们必须要更改我们之前写好的下层代码。这不符合开闭原则。所以我们不能在上层代码中将对下层的依赖写死,而应该采用接口的形式,在运行时动态的将下层具体实例对象的依赖进行注入,这就是依赖注入(DI)。
在不使用依赖注入的代码中,程序员需要手动的new出下层的具体实例对象,在使用完这个对象中需要手动的释放对象,虽然在Java中,释放对象这个操作由Java虚拟机的垃圾回收机制完成,但是事实上,对象实例的生命周期还是由程序员来维护的,换句话说,对象的控制权掌握在程序员手中。在进行依赖注入时,我们要通过配置文件实例化具体依赖的对象,放入全局的beanMap中,而代码中已经不再进行对象实例的创建,程序员不需要维护对象的生命周期,程序员没有对象的控制权。对象的生命周期由beanMap进行维护,控制权交由beanMap。这种控制权由程序员转为beanMap的过程,我们称之为控制反转(IOC)。
11.2 代码实现
配置文件:对象名、全类名、下层依赖对象
<?xml version="1.0" encoding="UTF-8" ?>
<beans>
<bean id="fruitDAO" class="dao.impl.FruitDAOImpl"/>
<bean id="fruit" class="controller.FruitController">
<property name="fruitService" ref="fruitService"/>
</bean>
<bean id="fruitService" class="service.impl.FruitServiceImpl">
<property name="fruitDAO" ref="fruitDAO"/>
</bean>
</beans>
Java代码:通过配置文件进行依赖注入
package ioc;
public interface BeanFactory {
public Object getBean(String id);
}
package ioc;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String, Object> beanMap = new HashMap<>();
ThreadLocal<String> threadLocal = new ThreadLocal<>();
/**
* 构造方法读取配置文件并为每个对象注入下层依赖
*/
public ClassPathXmlApplicationContext() {
try {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application-context.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(inputStream);
NodeList beanNodeList = document.getElementsByTagName("bean");
for (int i = 0; i < beanNodeList.getLength(); i++) {
Node beanNode = beanNodeList.item(i);
if (beanNode.getNodeType() == Node.ELEMENT_NODE){
Element beanElement = (Element) beanNode;
String beanId = beanElement.getAttribute("id");
String beanClass = beanElement.getAttribute("class");
Object beanObj = Class.forName(beanClass).getDeclaredConstructor().newInstance();
beanMap.put(beanId, beanObj);
}
}
for (int i = 0; i < beanNodeList.getLength(); i++) {
Node beanNode = beanNodeList.item(i);
if (beanNode.getNodeType() == Node.ELEMENT_NODE) {
Element beanElement = (Element) beanNode;
NodeList childNodes = beanElement.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
if (childNode.getNodeType() == Node.ELEMENT_NODE && "property".equals(childNode.getNodeName())){
Element propertyElement = (Element) childNode;
//拿到配置未见中的property节点中的name和ref值
String propertyName = propertyElement.getAttribute("name");
String propertyRef = propertyElement.getAttribute("ref");
//通过反射给父对象中的子对象的依赖进行注入!这就是依赖注入(DI)
//通过ref拿到子对象
Object refObj = beanMap.get(propertyRef);
//在beanMap中拿到父对象
Object beanObj = beanMap.get(beanElement.getAttribute("id"));
//给父对象的子对象属性赋值
Field field = beanObj.getClass().getDeclaredField(propertyName);
field.setAccessible(true);
field.set(beanObj, refObj);
}
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
@Override
public Object getBean(String id) {
return beanMap.get(id);
}
}
package service.impl;
import dao.FruitDAO;
import pojo.Fruit;
import service.FruitService;
import util.JDBCUtils;
import java.sql.Connection;
import java.util.List;
public class FruitServiceImpl implements FruitService {
// 具体的依赖设置为null,FruitDAO为接口
FruitDAO fruitDAO = null;
@Override
public List<Fruit> getFruitList(String keyword, Integer pageNum) {
Connection connection = null;
try {
connection = JDBCUtils.getConnection();
List<Fruit> fruits = fruitDAO.getPage(connection, pageNum, keyword);
return fruits;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(connection, null);
}
return null;
}
...
}
@WebServlet("*.do")
public class DispatcherServlet extends ViewBaseServlet {
private BeanFactory beanFactory;
public DispatcherServlet(){
}
@Override
public void init() throws ServletException {
super.init();
//在中央控制器类中创建实例类进行依赖注入
//这一步本不应该放在这里,应该在web程序启动的时候就创建该实例
//DispatcherServlet只是用来进行处理请求的组件
//ClassPathXmlApplicationContext是整个web项目的配置,包含整个web项目的bean容器
this.beanFactory = new ClassPathXmlApplicationContext();
}
...
}