I am trying to understand dependency injection before learning how to use Spring. My question is that in the following example of Setter-based Dependency Injection, why is there no constructor for the TextEditor class? Do we not need a constructor here? Many thanks for your help!!
我在学习如何使用Spring之前尝试理解依赖注入。我的问题是,在下面的基于Setter的依赖注入的例子中,为什么没有TextEditor类的构造函数?我们这里不需要构造函数吗?非常感谢您的帮助!!
( code sourced from: http://www.tutorialspoint.com/spring/setter_based_dependency_injection.htm)
(代码来自:http://www.tutorialspoint.com/spring/setter_based_dependency_injection.htm)
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker; //Q: Why not a constructor for TextEditor, but only a class variable?
// a setter method to inject the dependency.
public void setSpellChecker(SpellChecker spellChecker) {
System.out.println("Inside setSpellChecker." );
this.spellChecker = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
1 个解决方案
#1
2
If you don't declare a constructor explicitly, a default no-arg public constructor is added automatically. From the tutorials,
如果未明确声明构造函数,则会自动添加默认的无参数公共构造函数。从教程中,
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.
您不必为您的类提供任何构造函数,但在执行此操作时必须小心。编译器自动为没有构造函数的任何类提供无参数的默认构造函数。
And this constructor will be used by the Spring container to instantiate the object.
Spring容器将使用此构造函数来实例化对象。
#1
2
If you don't declare a constructor explicitly, a default no-arg public constructor is added automatically. From the tutorials,
如果未明确声明构造函数,则会自动添加默认的无参数公共构造函数。从教程中,
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.
您不必为您的类提供任何构造函数,但在执行此操作时必须小心。编译器自动为没有构造函数的任何类提供无参数的默认构造函数。
And this constructor will be used by the Spring container to instantiate the object.
Spring容器将使用此构造函数来实例化对象。