...中方法calculationRunner的参数0需要找不到类型为“ ...”的bean

时间:2019-03-11 07:57:25

标签: spring-boot java-11

环境:

jdk 11

spring boot 2.1.3

代码:

CupertinoTextField(
   placeholder: "Enter Email",
)

控制台:

 @SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @Bean
    public ApplicationRunner calculationRunner(Calculator calculator, 
            @Value("${lhs}") int lhs,
            @Value("${rhs}") int rhs, 
            @Value("${op}") char op) {
        return args -> calculator.calculate(lhs, rhs, op);
    }
}
public class Calculator {
    private final Collection<Operation> operations;

    public Calculator(Collection<Operation> operations) {
        this.operations = operations;
    }
    public void calculate(int lhs, int rhs, char op) {
        for (var operation : operations) {
            if (operation.handles(op)) {
                var result = operation.apply(lhs, rhs);
                System.out.printf("%d %s %d = %s%n", lhs, op, rhs, result);
                return;
            }
        }
        throw new IllegalArgumentException("Unknown operation " + op);
    }
}
public interface Operation {
    int apply(int lhs, int rhs);
    boolean handles(char op);
}
@Component
public class Addition implements Operation {
    @Override
    public int apply(int lhs, int rhs) {
        return lhs + rhs;
    }
    @Override
    public boolean handles(char op) {
        return '+' == op;
    }
}

结构 command line

我在“外部化属性”上研究了Spring Boot,请参阅问题。我确实知道如何处理。

希望您能帮助我解决问题,非常感谢。

1 个答案:

答案 0 :(得分:0)

您的calculationRunner方法期望将类型为Calculator的bean作为第一个参数。但是您的public class Calculator不是有效的Spring bean。考虑从Calculator方法的签名中删除calculationRunner,并在方法的主体内构造对象。或分别将Calculator定义为Spring bean(即添加@Service或类似的注释)。