zoukankan      html  css  js  c++  java
  • Java依赖注入

    转自:https://zhidao.baidu.com/question/1822852890089115988.html
    假设你编写了两个类,一个是人(Person),一个是手机(Mobile)。
    人有时候需要用手机打电话,需要用到手机的callUp方法。
    传统的写法是这样:
    Java code
    public class Person{
    public boolean makeCall(long number){
    Mobile mobile=new Mobile();
    return mobile.callUp(number);
    }
    }
    也就是说,类Person的makeCall方法对Mobile类具有依赖,必须手动生成一个新的实例new Mobile()才可以进行之后的工作。
    依赖注入的思想是这样,当一个类(Person)对另一个类(Mobile)有依赖时,不再该类(Person)内部对依赖的类(Moblile)进行实例化,而是之前配置一个beans.xml,告诉容器所依赖的类(Mobile),在实例化该类(Person)时,容器自动注入一个所依赖的类(Mobile)的实例。
    接口:
    Java code
    public Interface MobileInterface{
    public boolean callUp(long number);
    }
    Person类:
    Java code
    public class Person{
    private MobileInterface mobileInterface;
    public boolean makeCall(long number){
    return this.mobileInterface.callUp(number);
    }
    public void setMobileInterface(MobileInterface mobileInterface){
    this.mobileInterface=mobileInterface;
    }
    }
    在xml文件中配置依赖关系
    Java code
    <bean id="person" class="Person">
    <property name="mobileInterface">
    <ref local="mobileInterface"/>
    </property>
    </bean>
    <bean id="mobileInterface" class="Mobile"/>
    这样,Person类在实现拨打电话的时候,并不知道Mobile类的存在,它只知道调用一个接口MobileInterface,而MobileInterface的具体实现是通过Mobile类完成,并在使用时由容器自动注入,这样大大降低了不同类间相互依赖的关系。
    java依赖注入的方法:set注入,构造方法注入,接口注入。
  • 相关阅读:
    HUB_mysql学习笔记
    SQL学习笔记
    java_cmd_命令行
    JavaScript_2016_8_28
    linux mysql 安装配置
    solr 添加索引
    solr 查询 实例分析
    solr update接口常用方法
    solr schema.xml文档节点配置
    solr4.5安装配置 linux+tomcat6.0+mmseg4j-1.9.1分词
  • 原文地址:https://www.cnblogs.com/thiaoqueen/p/6760637.html
Copyright © 2011-2022 走看看