0
我可以使用基於字段注入沒問題注入System.in
:故障線路,在System.in使用構造器注入
import java.io.PrintStream;
@Component
public class Logger implements IReporter {
@Value("#{T(System).out}")
private PrintStream output;
public Logger() {
}
public void info(String message) {
output.println(String.format("[INFO] %s", message));
}
}
但我有麻煩做使用構造函數注入相同。
import java.io.PrintStream;
@Component
public class Logger implements IReporter {
private PrintStream output;
public Logger(@Value("#{T(System).out}") PrintStream output) {
this.output = output;
}
public void info(String message) {
output.println(String.format("[INFO] %s", message));
}
}
的錯誤是::
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'logger' defined in file [/User/h2o/Projects/hello-spring/hello-spring-1/target/classes/org.h2o.beans/impl/Logger.class]:
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.h2.beans.impl.Logger]:
No default constructor found; nested exception is java.lang.NoSuchMethodException: org.h2o.beans.impl.Logger.<init>()
如果我添加一個默認的構造,然後output
不會在和住宿有線,因爲綠豆沒有默認構造函數的代碼如下失敗null
。
我在這裏錯過了什麼?
的可能重複[?我如何執行基於構造函數的依賴注射使用註釋春](http://stackoverflow.com/questions/18117570/how-do-i-執行-構造爲基礎的依賴注入與 - 使用-annota彈簧) – h2o 2015-03-02 12:13:40