Spring based on set function dependency injection
When a container invokes a parameterless constructor or an argument-free static factory method to initialize your bean, the set-valued function is called by the container on your bean, and the DI is completed based on the value function.
Here is Texteditor.java:
PackageCom.tuorialsponit; Public classTextEditor {Privatespellchecker spellchecker; Public voidspellcheck () {spellchecker.checkspelling (); } Publicspellchecker Getspellchecker () {returnspellchecker; } Public voidSetspellchecker (spellchecker spellchecker) {System.out.println ("Inside Setspellchecker"); This. Spellchecker =spellchecker; } }
Spellchecker.java
Package Com.tuorialsponit; Public class spellchecker { public spellchecker () { System.out.println ("Inside spellchecker constructor. " ); } Public void checkspelling () { System.out.println ("Inside checkspelling.") ); }}
Contents of the Mainapp.java file:
Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Beans.xml");//HelloWorld obj1 = (HelloWorld) context.getbean ("HelloWorld");//System.out.println (Obj1.getmessage1 ());//System.out.println (Obj1.getmessage2 ());// //System.out.println ("-----------------------");//Helloindia obj2 = (helloindia) context.getbean ("Helloindia");//System.out.println (Obj2.getmessage1 ());//System.out.println (Obj2.getmessage2 ());//System.out.println (Obj2.getmessage3 ());//String message = Obj.getmessage ();//System.out.println (message);TextEditor TextEditor = (texteditor) context.getbean ("TextEditor"); Texteditor.spellcheck (); }
Contents of the configuration file Beans.xm:
<BeanID= "TextEditor"class= "Com.tuorialsponit.TextEditor"> <!--<constructor-arg ref= "Spellchecker" ></constructor-arg> - < Propertyname= "Spellchecker"ref= "Spellchecker"></ Property> </Bean> <BeanID= "Spellchecker"class= "Com.tuorialsponit.SpellChecker"> </Bean>
You should be aware of the differences between beans.xml files defined in constructor injection and based on set function injection. The only difference is that the label elements used are different. The second point you need to be aware of is that if you want to pass a reference to an object, you need to use the ref attribute of the tag, and if you want to pass a value directly, you should use the Value property.
Operation Result:
spring-Dependency injection based on set function