从注入方法上看,IOC可以分为三种类型:构造函数注入,set方法属性注入,接口方法注入,spring中支持前两种注入方式。
/** * 导演 * Created by qiqi on 2018/11/20 9:53 */ public class DirectorService { //剧本1 public void direct1() { //安排刘德华出演革离 GeLi geLi = new LiuDeHua(); //构造函数将革离注入到墨攻剧本 MoAttackService moAttackService = new MoAttackService(geLi); //城门守卫询问 moAttackService.cityGateAsk(); } //剧本2 public void direct2() { //安排刘德华出演革离 GeLi geLi = new LiuDeHua(); //set方法注入 MoAttackService moAttackService = new MoAttackService(); moAttackService.setGeLi(geLi); //城门守卫询问 moAttackService.cityGateAsk(); } //剧本3 public void direct3() { //安排刘德华出演革离 GeLi geLi = new LiuDeHua(); //接口方法注入 MoAttackService moAttackService = new MoAttackService(); moAttackService.injectGeLi(geLi); //城门守卫询问 moAttackService.cityGateAsk(); } }
/** * 墨攻剧本 * Created by qiqi on 2018/11/20 9:42 */ public class MoAttackService implements Acctor { private GeLi geLi; //构造函数注入 public MoAttackService(GeLi geLi) { this.geLi = geLi; } public MoAttackService() { } //set方法注入 public void setGeLi(GeLi geLi) { this.geLi = geLi; } //城门守卫询问 public void cityGateAsk() { geLi.responseAsk("I am MoAttack Geli"); } //重写接口方法 @Override public void injectGeLi(GeLi geLi) { geLi.responseAsk("I am MoAttack Geli"); } }
/** *接口方法 * Created by qiqi on 2018/11/20 10:16 */ public interface Acctor { void injectGeLi(GeLi geLi); }
/** * 革离 * Created by qiqi on 2018/11/20 9:45 */ public class GeLi { private String name; //回答 public String responseAsk(String name) { return this.name = name; } }
/** * Created by qiqi on 2018/11/20 9:55 */ public class LiuDeHua extends GeLi { }
由于接口注入需要额外声明一个接口,增加了类的数目,其本质与效果与set方法注入并无区别,所以不建议接口注入