广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java依赖注入容器超详细全面讲解
  • 574
分享到

Java依赖注入容器超详细全面讲解

Java依赖注入容器Java依赖注入 2023-01-12 09:01:23 574人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录一、依赖注入Dependency Injection二、解析2.1 典型的配置文件2.2 配置文件所对应的Java类2.3 定义解析器三、bean工厂(根据bean定义创建bea

一、依赖注入Dependency Injection

DI容器底层最基本的设计思路就是基于工厂模式。

DI容器的核心功能:配置解析、对象创建、对象声明周期。

完整的代码:Dependency Injection。

二、解析

通过配置,让DI容器知道要创建哪些对象。

DI容器读取文件,根据配置文件来创建对象。

2.1 典型的配置文件

下面是一个典型的配置文件:

<?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 配置文件所对应的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定义:


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方法
}

配置解析接口:


public interface BeanConfigParser {
    
    List<BeanDefinition> parse(InputStream in);
}

XML解析实现(使用Java自带的DOM解析类库):


public class BeanXmlConfigParser implements BeanConfigParser {
    
    @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);
        }
    }
    
    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;
    }
    
    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("未知类型");
        }
    }
    
    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工厂(根据bean定义创建bean对象)

根据bean工厂创建bean的对象:


public class BeansFactory {
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitions = new ConcurrentHashMap<>();
    
    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));
            }
        }
    }
    
    public Object getBean(String beanId) {
        BeanDefinition beanDefinition = beanDefinitions.get(beanId);
        checkState(Objects.nonNull(beanDefinition), "Bean is not defined:" + beanId);
        return createBean(beanDefinition);
    }
    
    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 容器接口


public interface ApplicationContext {
    Object getBean(String beanId);
    void loadBeanDefinitions(String configLocation);
}

4.2 XML容器


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);
    }
    
    public void loadBeanDefinitions(String configLocation) {
        try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(configLocation)) {
            if (in==null) {
                throw new RuntimeException("未发现配置文件:" + configLocation);
            }
            List<BeanDefinition> beanDefinitionList = beanConfigParser.parse(in);
            beansFactory.addBeanDefinitions(beanDefinitionList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    @Override
    public Object getBean(String beanId) {
        return beansFactory.getBean(beanId);
    }
}

五、使用DI容器


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()
}

到此这篇关于Java依赖注入容器超详细全面讲解的文章就介绍到这了,更多相关Java依赖注入容器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java依赖注入容器超详细全面讲解

本文链接: https://www.lsjlt.com/news/177451.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作