Construction-based dependency injection is completed when the container calls a class constructor with a set of parameters, each representing a dependency on another class.
Here’s an example:
TextEditor source code:
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck(a) { spellChecker.checkSpelling(); }}Copy the code
The TextEditor constructor has an argument that represents the SpellChecker dependency.
SpellChecker source code:
public class SpellChecker {
public SpellChecker(a){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(a) {
System.out.println("Inside checkSpelling."); }}Copy the code
Mainapp.java contents:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor"); te.spellCheck(); }}Copy the code
Beans.xml contents:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<! -- Definition for textEditor bean -->
<bean id="textEditor" class="com.sap.TextEditor">
<constructor-arg ref="spellChecker"/>
</bean>
<! -- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.sap.SpellChecker">
</bean>
</beans>
Copy the code
At the heart of injecting dependencies through constructors is this tag:
Single-step debugging observations: Creating a Spring IOC container:
Create TextEditor bean instance:
A dependency was detected in the constructor:
Depends on another bean: spellChecker
So a SpellChecker instance is also created:
Output:
Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.
Copy the code
If you want to pass a reference to an object, you need to use the ref attribute of the tag. If you want to pass the value directly, you should use the value attribute as shown above.
For more of Jerry’s original articles, please follow the public account “Wang Zixi “: