【发布时间】:2016-02-07 08:38:56
【问题描述】:
将@Autowired 注释到属性或在setter 中执行有什么区别?
据我所知,它们都有相同的结果,但是有什么理由使用其中一个而不是另一个?
更新(更简洁)
这有区别吗
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
还有这个
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
@Autowired
private SpellChecker spellChecker;
public TextEditor() {
System.out.println("Inside TextEditor constructor." );
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
【问题讨论】:
-
我不知道为什么这个问题的答案会是固执己见。我想知道在 setter 中或直接在属性中使用 @Autowired 是否有实际区别。不问哪个好,只要有区别就行了
标签: java spring dependency-injection