I can inject System.in
using field based injection with no problem:
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));
}
}
But I have trouble doing the same using constructor injection. The code below fails because the bean doesn't have a default constructor:
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));
}
}
The error is:
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>()
If I add a default constructor, then output
won't be wired in and stays null
.
What am I missing here?