环境:
JDK 11
春季靴2.1.3
代码:
@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;
}
}
控制台:
:: Spring Boot :: (v2.1.3.RELEASE)
ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-03-11 15:16:13.709 ERROR 4652 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method calculationRunner in com.example.demo.DemoApplication required a bean of type 'com.example.demo.Calculator' that could not be found.
Action:
Consider defining a bean of type 'com.example.demo.Calculator' in your configuration.
结构在此处输入图像描述
我在外部化属性上研究春季启动,请参阅问题。我知道如何处理。
我希望您能帮助我解决这个问题,非常感谢。
您的calculationRunner
方法期望Calculator
类型的Bean作为第一个参数。但是您的public class Calculator
不是有效的弹簧豆。考虑从calculationRunner
方法的签名中删除Calculator
,然后在该方法的身体中构造对象。或将Calculator
分别定义为弹簧豆(即添加@Service
或类似的注释)。