最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java依賴注入容器超詳細全面講解

 更新時間:2023年01月12日 08:31:09   作者:鯤鵬飛九萬里  
依賴注入(Dependency Injection)和控制反轉(zhuǎn)(Inversion of Control)是同一個概念。具體含義是:當某個角色(可能是一個Java實例,調(diào)用者)需要另一個角色(另一個Java實例,被調(diào)用者)的協(xié)助時,在 傳統(tǒng)的程序設(shè)計過程中,通常由調(diào)用者來創(chuàng)建被調(diào)用者的實例

一、依賴注入Dependency Injection

DI容器底層最基本的設(shè)計思路就是基于工廠模式。

DI容器的核心功能:配置解析、對象創(chuàng)建、對象聲明周期。

完整的代碼:Dependency Injection。

二、解析

通過配置,讓DI容器知道要創(chuàng)建哪些對象。

DI容器讀取文件,根據(jù)配置文件來創(chuàng)建對象。

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 配置文件所對應(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解析實現(xiàn)(使用Java自帶的DOM解析類庫):

/**
 * 解析XML,使用JDK自帶的DOM解析類庫
 */
public class BeanXmlConfigParser implements BeanConfigParser {
    /**
     * 根據(jù)流進行解析
     * @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對象)

根據(jù)bean工廠創(chuàng)建bean的對象:

/**
 * bean工廠:利用反射, 根據(jù)Bean定義創(chuàng)建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));
            }
        }
    }
    /**
     * 根據(jù)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);
    }
    /**
     * 根據(jù)Bean定義創(chuàng)建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);
    }
    /**
     * 根據(jù)配置文件路徑,把XML文件 解析成 bean定義對象
     * @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對象
     * @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()
}

到此這篇關(guān)于Java依賴注入容器超詳細全面講解的文章就介紹到這了,更多相關(guān)Java依賴注入容器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot使用Apache POI庫讀取Excel文件的操作詳解

    SpringBoot使用Apache POI庫讀取Excel文件的操作詳解

    在日常開發(fā)中,我們經(jīng)常需要處理Excel文件中的數(shù)據(jù),無論是從數(shù)據(jù)庫導(dǎo)入數(shù)據(jù)、處理數(shù)據(jù)報表,還是批量生成數(shù)據(jù),都可能會遇到需要讀取和操作Excel文件的場景,本文將詳細介紹如何使用Java中的Apache POI庫來讀取Excel文件,需要的朋友可以參考下
    2025-01-01
  • IDEA2023 配置使用Docker的詳細教程

    IDEA2023 配置使用Docker的詳細教程

    這篇文章主要介紹了IDEA2023 配置使用Docker的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-07-07
  • 如何解決Mybatis--java.lang.IllegalArgumentException: Result Maps collection already contains value for X

    如何解決Mybatis--java.lang.IllegalArgumentException: Result Maps

    這兩天因為項目需要整合spring、struts2、mybatis三大框架,但啟動的時候總出現(xiàn)這個錯誤,困擾我好久,折騰了好久終于找到問題根源,下面小編給大家分享下問題所在及解決辦法,一起看看吧
    2016-12-12
  • Java使用自定義注解實現(xiàn)函數(shù)測試功能示例

    Java使用自定義注解實現(xiàn)函數(shù)測試功能示例

    這篇文章主要介紹了Java使用自定義注解實現(xiàn)函數(shù)測試功能,結(jié)合實例形式分析了java自定義注解在函數(shù)測試過程中相關(guān)功能、原理與使用技巧,需要的朋友可以參考下
    2019-10-10
  • Java 大小寫最快轉(zhuǎn)換方式實例代碼

    Java 大小寫最快轉(zhuǎn)換方式實例代碼

    這篇文章主要介紹了Java 大小寫最快轉(zhuǎn)換方式實例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • 多個JDK版本(Java 8、Java 17、Java 21)下載和切換

    多個JDK版本(Java 8、Java 17、Java 21)下載和切換

    為了在實際中可以任意選擇所需的JDK版本,需要將多個JDK版本進行切換,本文主要介紹了多個JDK版本(Java 8、Java 17、Java 21)下載和切換,感興趣的可以了解一下
    2025-04-04
  • springboot]logback日志框架配置教程

    springboot]logback日志框架配置教程

    這篇文章主要介紹了springboot]logback日志框架配置,logback既可以通過application配置文件進行日志的配置,又可以通過logback-spring.xml進行日志的配置,本文給大家介紹的非常詳細,需要的朋友參考下吧
    2022-04-04
  • Java動態(tài)規(guī)劃篇之線性DP的示例詳解

    Java動態(tài)規(guī)劃篇之線性DP的示例詳解

    這篇文章主要通過幾個例題為大家詳細介紹一些Java動態(tài)規(guī)劃中的線性DP,文中的示例代碼講解詳細,對我們學習Java有一定的幫助,需要的可以參考一下
    2022-11-11
  • java  Swing基礎(chǔ)教程之圖形化實例代碼

    java Swing基礎(chǔ)教程之圖形化實例代碼

    這篇文章主要介紹了java Swing基礎(chǔ)教程之圖形化實例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • mybatis 如何利用resultMap復(fù)雜類型list映射

    mybatis 如何利用resultMap復(fù)雜類型list映射

    這篇文章主要介紹了mybatis 如何利用resultMap復(fù)雜類型list映射的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07

最新評論

分宜县| 绥棱县| 古交市| 新龙县| 鄂托克前旗| 瓦房店市| 平潭县| 久治县| 鱼台县| 温宿县| 汝城县| 甘泉县| 岑溪市| 兴国县| 攀枝花市| 棋牌| 铁力市| 宜宾县| 青田县| 伊吾县| 德阳市| 深圳市| 紫云| 卓尼县| 林西县| 黄石市| 札达县| 青海省| 丰城市| 田东县| 油尖旺区| 鲜城| 柘荣县| 若羌县| 高唐县| 湖州市| 株洲市| 曲沃县| 星子县| 胶州市| 洞口县|