• Spring-基于构造函数的依赖注入


    Spring基于构造函数的依赖注入

    当容器调用带有一组参数的类构造函数时,基于构造函数的DI就完成了,其中每个参数代表一个对其他类的依赖。

    TextEditor.java文件的内容:

    package com.tuorialsponit;
    
    public class TextEditor {
        private SpellChecker spellChecker;
        public TextEditor(SpellChecker spellChecker){
            this.spellChecker = spellChecker;
        }
        
        public void spellCheck() {
            spellChecker.checkSpelling();
        }
    }

    下面是另一个依赖类文件SpellChecker.java内容

    package com.tuorialsponit;
    
    public class SpellChecker {
        public SpellChecker(){
            System.out.println("Inside SpellChecker constructor.");
        }
        
        public void checkSpelling(){
            System.out.println("Inside checkSpelling.");
        }
    }

    以下是MainApp.java文件的内容

    public class MainApp {
        public static void main(String[] args){
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //    
            TextEditor textEditor = (TextEditor) context.getBean("textEditor");
            textEditor.spellCheck();
        }
    }

    下面是配置文件Beans.xml的内容,它有基于构造函数注入的配置:

    <bean id="textEditor" class="com.tuorialsponit.TextEditor">
             <constructor-arg ref="spellChecker"></constructor-arg>
         </bean>
         
         <bean id="spellChecker" class="com.tuorialsponit.SpellChecker">
         </bean>

    运行结果:

  • 相关阅读:
    【重点】Java大厂面试10个知识点汇总
    TEC-2机微程序设计
    Component 'TABCTL32.OCX'错误的处理方法
    Azure DevOps的使用入门
    Mac + VMware Fusion + Windows 11尝鲜
    Golang接口类型-下篇
    Golang接口类型-上篇
    基于Python实现原生的登录验证码
    一套帮助你理解C语言的测试题(转)
    KMP算法详解
  • 原文地址:https://www.cnblogs.com/fangpengchengbupter/p/7816012.html
Copyright © 2020-2023  润新知