首页 > 解决方案 > 为什么Spring boot在处理void函数的@Bean注解时会偏向

问题描述

我的配置类中有 2 个使用@Bean注释的函数,一个函数返回一个 void,我希望第二个函数也返回 void。

但是当我编译 Spring boot 并运行我的应用程序时,我得到了这个错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reciveMessage' defined in class path resource [com/XXXXXX/Configuration/Configuration.class]: Invalid factory method 'reciveMessage': needs to have a non-void return type!

但是如果我删除第二种方法,我没有收到任何错误消息,Spring boot 处理我的第一个 void 方法没有任何问题。

所以我的问题是为什么会发生这种情况,为什么它运行我的第一个 void 函数而不是我的第二个 void 函数。

有没有办法让我添加多个带有@Bean注释的 void 函数。

这是我的代码

package com.beanTester.start.beanTester;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.*;

@Configuration
 class configuration {

    private Logger logger;


    @Value("${logConfigPath}")
    private String path;

    private LogManager manager = LogManager.getLogManager();

    @Bean
    public void logging_init() throws IOException {
        FileInputStream inputStream;
        logger = Logger.getLogger(this.getClass().getPackage().getName());
        try {
            inputStream = new FileInputStream(path);
            manager.readConfiguration(inputStream);
        } catch (FileNotFoundException e) {
            logger.setLevel(Level.INFO);
            FileHandler logFile = new FileHandler("DefaultLogger.log");
            logFile.setFormatter(new SimpleFormatter());
            logger.setParent(Logger.getGlobal());
            logger.addHandler(logFile);
        }
    }

    @Bean
    public String sendMessage() {
        return "I just send a message";
    }

    @Bean
    public void reciveMessage(String message) {
        System.out.println(" I recived a message called " + message);
    }

}

标签: javaspringspring-boot

解决方案


推荐阅读