解决Springboot无法注入RestTemplate

1,504 阅读1分钟

报错信息

2021-04-22 13:23:28.574  INFO 5308 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-22 13:23:28.647 ERROR 5308 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field restTemplate in com.mundo.DemoEurekaConsumerApplication 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.

【解决方法】:

在 Spring Boot 项目启动类 xxxApplication 中,设置手动引入 RestTemplate 相关配置,代码如下:

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

然后在别的类中注入,启动就不会报错了,如:

public class TestService {
	@Autowired
	private RestTemplate restTemplate;
	public void service() {
		restTemplate.getForObject("", String.class);
	}
}