亲宝软件园·资讯

展开

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

鲲鹏飞九万里 人气:0

一、依赖注入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定义:

/**
 * 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解析实现(使用Java自带的DOM解析类库):

/**
 * 解析XML,使用JDK自带的DOM解析类库
 */
public class BeanXmlConfigParser implements BeanConfigParser {
    /**
     * 根据流进行解析
     * @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);
        }
    }
    /**
     * 创建构造函数
     * @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;
    }
    /**
     * 获取构造函数 参数的值
     * @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("未知类型");
        }
    }
    /**
     * 获取构造函数的类型, 注意原始类型的 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工厂(根据bean定义创建bean对象)

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

/**
 * bean工厂:利用反射, 根据Bean定义创建Bean对象
 */
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));
            }
        }
    }
    /**
     * 根据beanId获取Bean对象
     * @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);
    }
    /**
     * 根据Bean定义创建Bean对象
     * @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);
    }
    /**
     * 根据配置文件路径,把XML文件 解析成 bean定义对象
     * @param 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);
        }
    }
    /**
     * 从Bean工厂获取Bean对象
     * @param beanId
     * @return
     */
    @Override
    public Object getBean(String beanId) {
        return beansFactory.getBean(beanId);
    }
}

五、使用DI容器

/**
 * 使用DI容器,从获取中获取Bean对象
 */
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()
}

加载全部内容

相关教程
猜你喜欢
用户评论