IOC is one of the two cores of spring: The core of the IOC is decoupling.
For example: There are 2 classes can be classes, the principal designated teachers to attend classes, the code is as follows
Package com.hongcong.test; Public class Class1 { publicvoid teach () { System.out.println ("one Class in Class");} }
Package com.hongcong.test; Public class Class2 { publicvoid teach () { System.out.println ("Class two is in class");} }
Teacher
Package com.hongcong.test; Public class Teacher { publicvoid Doteach () { new Class1 (); Class1.teach (); }}
Principal
package Com.hongcong.service; import Com.hongcong.test.Class1; import Com.hongcong.test.Class2; import Com.hongcong.test.teacher; public class Principal { public static void main (string[] args) {T Eacher teacher = new teacher (); Teacher.doteach (); }}
At this time to run the headmaster, class began. But if the headmaster wants the teacher to go to class two, either revise the teacher's method, or add the teacher's method and revise the headmaster's method. As you can see, the code at this point is coupled together. This time you can use the IOC's ideas to redesign the program, the code is as follows:
Define a class interface, then class one and class two to implement this interface:
Package com.hongcong.test; Public Interface Teachinterface { publicvoid teach ();}
package com.hongcong.test; public class Class1 implements teachinterface{ public void teach ( {SYSTEM.OUT.PRINTLN ( class in class "
package com.hongcong.test; public class Class2 implements teachinterface{ public void teach ( {SYSTEM.OUT.PRINTLN ( class two in class "
Package com.hongcong.test; Public class Teacher { private teachinterface teachinterface; Public void setteachinterface (Teachinterface teachinterface) { this. Teachinterface= teachinterface; } Public void Doteach () { teachinterface.teach (); }}
PackageCom.hongcong.service;ImportCom.hongcong.test.Class1;ImportCom.hongcong.test.Class2;ImportCom.hongcong.test.teacher; Public classPrincipal { Public Static voidMain (string[] args) {Teacher Teacher=Newteacher (); Teacher.setteachinterface (NewClass2 ()); Teacher.doteach (); }}
At this time, if the headmaster wants to let the teacher go to class, only need to modify teacher.setteachinterface (new Class2 ()); The parameters in the method are available. The teacher has been and to which class class completely has no relationship, as long as the headmaster next instruction.
The Spring core IOC