java - 考虑在您的配置中定义 * 类型的 bean

标签 java spring

我不明白此错误或任何解决该错误的步骤。建议的行动对我来说没有多大意义。我看到很多人问这样的问题,但我仍然不明白根本的问题。

我得到的错误是:

Description:
Parameter 0 of constructor in com.yrc.mcc.core.batch.listener.ChunkSizeListener required a bean of type 'java.io.File' that could not be found.**

Action:
Consider defining a bean of type 'java.io.File' in your configuration.

我的类(class)内容:

@Component
public class ChunkSizeListener extends StepListenerSupport<Object, Object> {

    private FileWriter fileWriter;

    public ChunkSizeListener(File file) throws IOException {
        fileWriter = new FileWriter(file, true);
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        try {
            fileWriter.close();
        } catch (IOException e) {
            System.err.println("Unable to close writer");
        }
        return super.afterStep(stepExecution);
    }

    @Override
    public void beforeChunk(ChunkContext context) {
        try {
            fileWriter.write("your custom header");
            fileWriter.flush();
        } catch (IOException e) {
            System.err.println("Unable to write header to file");
        }
    }
}

最佳答案

很清楚了!

Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies

因此,在您的情况下,spring 希望有一个 File 类型的 bean(这不是您的情况)作为 bean,所以您可以做的是更新您的代码,向您的类添加默认构造函数,如下所示:

@Component
public class ChunkSizeListener extends StepListenerSupport<Object, Object> {

    private FileWriter fileWriter;

    public ChunkSizeListener() {
        // not sure if you should keep the super() or not
        super();
    }

    public ChunkSizeListener(File file) throws IOException {
        fileWriter = new FileWriter(file, true);
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        try {
            fileWriter.close();
        } catch (IOException e) {
            System.err.println("Unable to close writer");
        }
        return super.afterStep(stepExecution);
    }

    @Override
    public void beforeChunk(ChunkContext context) {
        try {
            fileWriter.write("your custom header");
            fileWriter.flush();
        } catch (IOException e) {
            System.err.println("Unable to write header to file");
        }
    }
}

关于java - 考虑在您的配置中定义 * 类型的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55142905/

相关文章:

java - DataOutputStream模拟抛出空指针异常

java - 如何与 OpenSessionInViewInterceptor 结合重新打开 Spring session

java - Spring map 合并所有值

java - 引导 Swing 应用程序

java - 将变量从 MainActivity 传递到另一个 Activity 到选项卡 Fragment

java - 解析 Rest API 响应

java - 将安全 token 功能从 C# 重新创建为 Java

java - 颜色标题不起作用

java - Bean创建异常: Error creating bean with name 'sessionFactory'

java - Gradle 构建不下载依赖项