0

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?

TheFooProgrammer
  • 2,439
  • 5
  • 28
  • 43
  • possible duplicate of [How do I perform Constructor-based dependency injection with Spring using annotations?](http://stackoverflow.com/questions/18117570/how-do-i-perform-constructor-based-dependency-injection-with-spring-using-annota) – TheFooProgrammer Mar 02 '15 at 12:13

1 Answers1

0

Oops! It needed the @Autowired constructor:

@Component
public class Logger implements IReporter {

    private PrintStream output;

    @Autowired  
    public Logger(@Value("#{T(System).out}") PrintStream output) {
        this.output = output;
    }

    public void info(String message) {
        output.println(String.format("[INFO] %s", message));
    }

}
TheFooProgrammer
  • 2,439
  • 5
  • 28
  • 43