记录以下今天遇到的一个小bug。
使用SpringCloud框架,在Controller层调用其他模型是,注入了RestTemplate,但是却抛出了异常如下:
2021-07-06 20:43:38.534 WARN 9484 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController': Unsatisfied dependency expressed through field 'template'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2021-07-06 20:43:38.536 INFO 9484 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-07-06 20:43:38.543 INFO 9484 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-07-06 20:43:38.631 ERROR 9484 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field template in com.lbk.order.controller.OrderController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
Process finished with exit code 1
这是因为注入时,spring并没有找到这个玩意儿
解决方法:
在启动类里加上这段代码:
//注入时实例化RestTemplate对象。
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
再重新启动一下项目,成功运行!