Spring's IOC is mainly dependent injection, there is a dependency injection based on the constructor and through the setting value injection, here I only simple implementation of the method of value injection, through spring dependency management, we can easily understand the dependencies between the layers, reducing the coupling between the layers, We can not focus on the management and creation of objects, we just need to go to the bean factory to apply, so that our more attention can be put into the real code implementation, not to care about the creation and destruction of code. , and then simply set the value to inject.
- Let's start by simply creating a class of students and teachers
Public class Student { publicvoid Outhi () { System.out.println ("I am a student");} }
public class teacher { Student Stu; public Student Getstu () { return Stu; public void Setstu (Student Stu) { Stu; public void Lalal () {Stu.outhi (); System.out.println ( "Lalala" ); }}
Notice that the teacher class here depends on the student class, that is, the need to call the student object in the teacher class, here we use the method of setting value injection.
- Next you need to go to the XML file to do the corresponding configuration
<bean name= "Stu" class= "Com.domain.Student" ></bean> <bean name= "Teacher" class= "Com.domain.teacher" > <property name= "Stu" ref= "Stu" ></property> </bean >
- Finally, apply the corresponding object in the main function
Public Static void Main (string[] args) { // TODO auto-generated method stub new Classpathxmlapplicationcontext ("Applicationcontext.xml"); Teacher Tea= (teacher) Ctx.getbean ("Teacher"); Tea.lalal (); }
Simple use of IOC in spring