构造器与Setter注入依赖

2.1 注入依赖

依赖注入(DI)背后的基本原理是对象之间的依赖关系(即一起工作的其他对象)只会通过以下几种方式来实现:构造器的参数,工厂方法的参数,或给构造器或者工厂方法创建对象设置属性。因此,容器的工作就是创建哪些bean时注入这些依赖关系。相对于有bean自己来控制其实例化,直接在构造器中指定依赖关系或者类似服务定位器(Service Locator)模式这3种自主控制依赖关系注入的方法来说,控制从根本上发生了倒转,这也就是控制反转的由来。

2.2 构造器注入

基于构造器的依赖注入(DI)通过调用带参数的构造器来实现,每个参数代表着一个依赖

依赖注入例子:

pulic class SimpeMovieLister{
//the SimpleMovieLister has a dependency on a MovieFinder
private MovieFinder movieFinder;

//a construstor so that the Spring container can 'inject' a MovieFinder
public SimpleMovieLister(MovieFinder movieFinder){
    this.movieFinder = movieFinder;
}
}

2.2.1 构造器参数解析

构造器参数解析根据参数类型进行匹配,如果bean的构造器参数烈性定义非常明确,那么在bean被实例化的时候,bean定义构造器参数的定义顺序就是这些参数额顺序,依次进行匹配。

package x.y;
public class Foo{
public Foo(Bar bar,Baz,baz){
    //---
}
}

顺序 Bar,Baz

已知该bean的参数类型,匹配也没有问题。但是当使用简单类型时,比如<value>true<value>,Spring将无法知道该值的类型。不借助其他帮助,将无法仅仅根据参数类型进行匹配。

package examples;
public class ExampleBean{
// no of years to the calculate the Ultimate Answer
private int years;
// The Answer to Life,the Universe,and Everything
private String ultimateAnswer;
   public ExampleBean(int years,String ultimateAnswer){
       this.years = years;
       this.ultimateAnser = ultimateAnswer;
  }
}

针对上述场景解决方案:

可以通过'type'属性来显示指定哪些简单类型的构造参数的类型

eg:

<bean id="exampleBean" class="examples.ExampleBean">
   <constructor-arg index="0" value="72"/> --years
   <constructor-arg index="1" value="72"/> --ultimateAnswer
   
</bean>
-- 通过索引属性不但可以解决简单属性的混乱问题,还可以解决有可能相同类型的2个构造参数的混淆问题,index从0开始

2.3 Setter注入

通过调用无参构造器或午餐static工厂方法实例化bean之后,调用改bean的setter方法,即可实现基于setter的。

eg:setter注入依赖

public class SimpeMovicLister{
   private MovieFinder movieFinder;
   
   public void setMovieFinder(MovieFinder movieFinder){
       this.movieFindr = movieFinder;
  }
}

 --引用Spring中文文档

posted @ 2021-09-15 10:58  扣扣M  阅读(205)  评论(0)    收藏  举报