Java依賴注入容器超詳細(xì)全面講解
一、依賴注入Dependency Injection
DI容器底層最基本的設(shè)計(jì)思路就是基于工廠模式。
DI容器的核心功能:配置解析、對(duì)象創(chuàng)建、對(duì)象聲明周期。
完整的代碼:Dependency Injection。

二、解析
通過(guò)配置,讓DI容器知道要?jiǎng)?chuàng)建哪些對(duì)象。
DI容器讀取文件,根據(jù)配置文件來(lái)創(chuàng)建對(duì)象。
2.1 典型的配置文件
下面是一個(gè)典型的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="productInfo" class="com.hef.review.designpatterns.creational.di.beans.ProductInfo">
<constructor-arg type="String" value="P01"/>
<constructor-arg type="int" value="200"/>
</bean>
<bean id="productSell" class="com.hef.review.designpatterns.creational.di.beans.ProductSell">
<constructor-arg ref="productInfo"/>
</bean>
</beans>
2.2 配置文件所對(duì)應(yīng)的Java類
public class ProductInfo {
private String productName;
private int productVersion;
public ProductInfo(String productName, int productVersion) {
this.productName = productName;
this.productVersion = productVersion;
}
// 省略 getter 和 setter
}
public class ProductSell {
private ProductInfo productInfo;
public ProductSell(ProductInfo productInfo) {
this.productInfo = productInfo;
}
public void sell() {
System.out.println("銷售:" + productInfo);
}
// 省略 getter 和 setter
}
2.3 定義解析器
Bean定義:
/**
* Bean定義
*/
public class BeanDefinition {
private String id;
private String className;
private List<ConstructorArg> constructorArgs = new ArrayList<>();
private Scope scope = Scope.SINGLETON;
private boolean lazyInit = false;
public BeanDefinition(){}
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
// 省略getter 和 setter方法
}
配置解析接口:
/**
* 將XML配置解析成 Bean定義
*/
public interface BeanConfigParser {
/**
* 解析Bean定義
* @param in
* @return
*/
List<BeanDefinition> parse(InputStream in);
}
XML解析實(shí)現(xiàn)(使用Java自帶的DOM解析類庫(kù)):
/**
* 解析XML,使用JDK自帶的DOM解析類庫(kù)
*/
public class BeanXmlConfigParser implements BeanConfigParser {
/**
* 根據(jù)流進(jìn)行解析
* @param in
* @return
*/
@Override
public List<BeanDefinition> parse(InputStream in) {
try {
List<BeanDefinition> result = new ArrayList<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(in);
doc.getDocumentElement().normalize();
NodeList beanList = doc.getElementsByTagName("bean");
for (int i = 0; i < beanList.getLength(); i++) {
Node node = beanList.item(i);
if (!Objects.equals(node.getNodeType(), Node.ELEMENT_NODE)) continue;
Element element = (Element) node;
BeanDefinition beanDefinition = new BeanDefinition(element.getAttribute("id"), element.getAttribute("class"));
if (element.hasAttribute("scope")
&& StringUtils.equals(element.getAttribute("scope"), BeanDefinition.Scope.PROTOTYPE.name())) {
beanDefinition.setScope(BeanDefinition.Scope.PROTOTYPE);
}
if (element.hasAttribute("lazy-init")
&& Boolean.valueOf(element.getAttribute("lazy-init"))) {
beanDefinition.setLazyInit(true);
}
List<BeanDefinition.ConstructorArg> constructorArgs = createConstructorArgs(element);
if (CollectionUtils.isNotEmpty(constructorArgs)) {
beanDefinition.setConstructorArgs(constructorArgs);
}
result.add(beanDefinition);
}
return result;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 創(chuàng)建構(gòu)造函數(shù)
* @param element
* @return
*/
private List<BeanDefinition.ConstructorArg> createConstructorArgs(Element element) {
List<BeanDefinition.ConstructorArg> result = new ArrayList<>();
NodeList nodeList = element.getElementsByTagName("constructor-arg");
if (nodeList.getLength()==0) return result;
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (!Objects.equals(node.getNodeType(), Node.ELEMENT_NODE)) continue;
Element ele = (Element) node;
BeanDefinition.ConstructorArg arg = new BeanDefinition.ConstructorArg();
if (ele.hasAttribute("type") && StringUtils.isNoneBlank(ele.getAttribute("type"))) {
String type = ele.getAttribute("type");
String value = ele.getAttribute("value");
arg.setType(fetchClassType(type));
arg.setArg(fetchArgValue(type, value));
arg.setRef(false);
}else if (ele.hasAttribute("ref")) {
arg.setRef(true);
arg.setArg(ele.getAttribute("ref"));
}
result.add(arg);
}
return result;
}
/**
* 獲取構(gòu)造函數(shù) 參數(shù)的值
* @param typeValue
* @param value
* @return
*/
private Object fetchArgValue(String typeValue, String value) {
if (StringUtils.equals(typeValue, "int") || StringUtils.contains(typeValue, "Integer")) {
return Integer.parseInt(value);
}else if (StringUtils.contains(typeValue, "String")) {
return value;
} else {
throw new RuntimeException("未知類型");
}
}
/**
* 獲取構(gòu)造函數(shù)的類型, 注意原始類型的 Class表示
* @param typeValue
* @return
*/
private Class<?> fetchClassType(String typeValue) {
if (StringUtils.equals(typeValue, "int")){
return Integer.TYPE;
} else if(StringUtils.contains(typeValue, "Integer")) {
return Integer.class;
}else if (StringUtils.contains(typeValue, "String")) {
return String.class;
} else {
throw new RuntimeException("未知類型");
}
}
}三、bean工廠(根據(jù)bean定義創(chuàng)建bean對(duì)象)
根據(jù)bean工廠創(chuàng)建bean的對(duì)象:
/**
* bean工廠:利用反射, 根據(jù)Bean定義創(chuàng)建Bean對(duì)象
*/
public class BeansFactory {
private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, BeanDefinition> beanDefinitions = new ConcurrentHashMap<>();
/**
* 向Bean工廠中,添加Bean定義
* @param beanDefinitionList
*/
public void addBeanDefinitions(List<BeanDefinition> beanDefinitionList) {
for (BeanDefinition beanDefinition : beanDefinitionList) {
this.beanDefinitions.putIfAbsent(beanDefinition.getId(), beanDefinition);
}
for (BeanDefinition beanDefinition : beanDefinitionList) {
if (!beanDefinition.isLazyInit() && beanDefinition.isSingleton()) {
singletonObjects.put(beanDefinition.getId(), createBean(beanDefinition));
}
}
}
/**
* 根據(jù)beanId獲取Bean對(duì)象
* @param beanId
* @return
*/
public Object getBean(String beanId) {
BeanDefinition beanDefinition = beanDefinitions.get(beanId);
checkState(Objects.nonNull(beanDefinition), "Bean is not defined:" + beanId);
return createBean(beanDefinition);
}
/**
* 根據(jù)Bean定義創(chuàng)建Bean對(duì)象
* @param beanDefinition
* @return
*/
private Object createBean(BeanDefinition beanDefinition) {
if (beanDefinition.isSingleton() && singletonObjects.containsKey(beanDefinition.getId())) {
return singletonObjects.get(beanDefinition.getId());
}
Object result = null;
try {
Class<?> beanClass = Class.forName(beanDefinition.getClassName());
List<BeanDefinition.ConstructorArg> constructorArgs = beanDefinition.getConstructorArgs();
if (CollectionUtils.isEmpty(constructorArgs)) {
result = beanClass.newInstance();
} else {
Class[] argClasses = new Class[constructorArgs.size()];
Object[] argObjects = new Object[constructorArgs.size()];
for (int k = 0; k < constructorArgs.size(); k++) {
BeanDefinition.ConstructorArg arg = constructorArgs.get(k);
if (!arg.isRef()) {
argClasses[k] = arg.getType();
argObjects[k] = arg.getArg();
} else {
BeanDefinition refBeanDefinition = beanDefinitions.get(arg.getArg());
checkState(Objects.nonNull(refBeanDefinition), "Bean is not defined: " + arg.getArg());
argClasses[k] = Class.forName(refBeanDefinition.getClassName());
argObjects[k] = createBean(refBeanDefinition);
}
}
result = beanClass.getConstructor(argClasses).newInstance(argObjects);
}
if (Objects.nonNull(result) && beanDefinition.isSingleton()) {
singletonObjects.putIfAbsent(beanDefinition.getId(), result);
return singletonObjects.get(beanDefinition.getId());
}
return result;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}四、DI容器(上下文)
4.1 容器接口
/**
* DI容器接口
*/
public interface ApplicationContext {
Object getBean(String beanId);
void loadBeanDefinitions(String configLocation);
}
4.2 XML容器
/**
* XML DI容器上下文
*/
public class ClassPathXmlApplicationContext implements ApplicationContext {
private BeansFactory beansFactory;
private BeanConfigParser beanConfigParser;
public ClassPathXmlApplicationContext(String configLocation) {
this.beansFactory = new BeansFactory();
this.beanConfigParser = new BeanXmlConfigParser();
loadBeanDefinitions(configLocation);
}
/**
* 根據(jù)配置文件路徑,把XML文件 解析成 bean定義對(duì)象
* @param configLocation
*/
public void loadBeanDefinitions(String configLocation) {
try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(configLocation)) {
if (in==null) {
throw new RuntimeException("未發(fā)現(xiàn)配置文件:" + configLocation);
}
List<BeanDefinition> beanDefinitionList = beanConfigParser.parse(in);
beansFactory.addBeanDefinitions(beanDefinitionList);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 從Bean工廠獲取Bean對(duì)象
* @param beanId
* @return
*/
@Override
public Object getBean(String beanId) {
return beansFactory.getBean(beanId);
}
}
五、使用DI容器
/**
* 使用DI容器,從獲取中獲取Bean對(duì)象
*/
public class Demo {
public static void main(String[] args) {
// testReadResourceXML();
// testParseXML();
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Object productInfo = context.getBean("productInfo");
System.out.println(productInfo);
ProductSell productSell = (ProductSell)context.getBean("productSell");
productSell.sell();
}
// 省略 testReadResourceXML() 和 testParseXML()
}
到此這篇關(guān)于Java依賴注入容器超詳細(xì)全面講解的文章就介紹到這了,更多相關(guān)Java依賴注入容器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Maven 搭建 Spring MVC 本地部署Tomcat的詳細(xì)教程
這篇文章主要介紹了使用Maven 搭建 Spring MVC 本地部署Tomcat,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
教你用java完美封裝微信模板消息的發(fā)送動(dòng)態(tài)
這篇文章主要介紹了教你用java完美封裝微信模板消息的發(fā)送動(dòng)態(tài),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04
Spring cloud Eureka注冊(cè)中心搭建的方法
這篇文章主要介紹了Spring cloud Eureka注冊(cè)中心搭建的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Maven項(xiàng)目繼承實(shí)現(xiàn)過(guò)程圖解
這篇文章主要介紹了Maven項(xiàng)目繼承實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

