Spring constructor-based dependency injection
When a container invokes a class constructor with a set of parameters, the constructor-based di is completed, where each parameter represents a dependency on another class.
Contents of the Texteditor.java file:
Package Com.tuorialsponit; Public class texteditor { private spellchecker spellchecker; Public TextEditor (spellchecker spellchecker) { this. Spellchecker= spellchecker; } publicvoid spellcheck () { spellchecker.checkspelling (); }}
The following is another dependent class file Spellchecker.java content
Package Com.tuorialsponit; Public class spellchecker { public spellchecker () { System.out.println ("Inside spellchecker constructor. " ); } Public void checkspelling () { System.out.println ("Inside checkspelling.") ); }}
The following is the contents of the Mainapp.java file
Public class Mainapp { publicstaticvoid main (string[] args) { new Classpathxmlapplicationcontext ("Beans.xml"); // TextEditor TextEditor = (texteditor) context.getbean ("TextEditor"); Texteditor.spellcheck (); }}
The following is the content of the configuration file Beans.xml, which has a configuration based on constructor injection:
<BeanID= "TextEditor"class= "Com.tuorialsponit.TextEditor"> <Constructor-argref= "Spellchecker"></Constructor-arg> </Bean> <BeanID= "Spellchecker"class= "Com.tuorialsponit.SpellChecker"> </Bean>
Operation Result:
spring-Dependency Injection based on constructors