使用构造函数注入麻烦接线System.in

时间:2015-03-02 12:09:12

标签: java spring dependency-injection constructor-injection

我可以使用基于字段的注入注入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));
    }

}

但是使用构造函数注入我也无法做同样的事情。下面的代码失败,因为bean没有默认构造函数:

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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

糟糕!它需要@Autowired构造函数:

@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));
    }

}