常用的依赖注入方式:
**1、构造方法注入;2、set属性注入;3、接口注入
构造函数注入
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.set属性注入
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();
}
}
3、接口注入
public class StupidStudent {
public 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);
}
}