zoukankan      html  css  js  c++  java
  • 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>

    运行结果:

  • 相关阅读:
    准确率99.9%的离线IP地址定位库
    手写一个消息队列以及延迟消息队列
    rabbitmq介绍
    污点和亲和力高级调度方式
    ceph
    Vue作业
    label和labelSeletor
    http状态简记
    数据库
    作业
  • 原文地址:https://www.cnblogs.com/fangpengchengbupter/p/7816012.html
Copyright © 2011-2022 走看看