依赖注入的实现方法

构造器注入
  • 在初始化的时候,被依赖对象通过构造函数的传参注入到依赖对象
  • 不够灵活,如果需要的依赖对象很多,那么参数列表很长
public class DemoImpl {   
  
  private IService iService; 

  public DemoImpl (IService iService){      
     this.iService = iService;    
  } 

}
setter方法注入
  • 通过调用成员变量的set方法注入
  • 可以选择需要注入的对象
  • 如果初始化之后没注入被依赖对象就没法使用
public class DemoImpl {   
  
  private IService iService; 

  public void setiService(IService iService) {
        this.iService = iService;
  }

}
接口注入
  • 实现一个指定的接口,这个接口里面有一个方法专门用于依赖注入,这个方法的参数就是依赖注入的对象
  • 侵入性太强
posted @ 2022-07-04 19:07  张三丰学Java  阅读(78)  评论(0编辑  收藏  举报