【问题标题】:Trouble wiring-in System.in using constructor injection使用构造函数注入在 System.in 中接线时遇到问题
【发布时间】:2015-03-02 12:09:11
【问题描述】:

我可以毫无问题地使用基于字段的注入来注入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

我在这里错过了什么?

【问题讨论】:

标签: java spring dependency-injection constructor-injection


【解决方案1】:

哎呀!它需要@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));
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多