1、构造方法依赖注入
public class StupidStudent {
private SmartStudent smartStudent;
public StupidStudent(SmartStudent smartStudent) {
this.smartStudent = smartStudent;
}
public doHomewrok() {
smartStudent.doHomework();
System.out.println("学渣抄作业");
}
}
public class StudentTest {
public static void main(String[] args) {
SmartStudent smartStudent = new SmartStudent();
StupidStudent stupidStudent = new StupidStudent(smartStudent);
stupidStudent.doHomework();
}
}
这种方式好比学渣从一开始就赖上了一个学霸,并且和这个学霸建立了长期合作关系。
2、setter方法注入
public class StupidStudent {
private SmartStudent smartStudent;
public void setSmartStudent(SmartStudent smartStudent) {
this.smartStudent = smartStudent;
}
public doHomewrok() {
smartStudent.doHomework();
System.out.println("学渣抄作业");
}
}
public class StudentTest {
public static void main(String[] args) {
SmartStudent smartStudent = new SmartStudent();
StupidStudent stupidStudent = new StupidStudent();
stupidStudent.setSmartStudent(smartStudent);
stupidStudent.doHomework();
}
}
这种方式学霸和学渣只是暂时的合作关系,如果学渣赖上了另一个学霸(调用set()方法传入了另一个对象),那么学渣和学霸的合作关系就结束了。
3、接口注入
public class StupidStudent {
public void doHomewrok(SmartStudent smartStudent) {
smartStudent.doHomework();
System.out.println("学渣抄作业");
}
}
public class StudentTest {
public static void main(String[] args) {
SmartStudent smartStudent = new SmartStudent();
StupidStudent stupidStudent = new StupidStudent();
stupidStudent.doHomework(smartStudent);
}
}
采用这种注入方式,学渣只是在做作业时,才临时抱佛脚地找一下学霸。