天行健,君子以自强不息;地势坤,君子以厚德载物。
每个人都有惰性,但不断学习新东西是好好生活的根本,共勉!
文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。
场景描述(产生环境)
在使用restTemplate封装的工具调用接口时,自动注入报错
restTemplate工具类相关文章链接:
请求调用RestTemplate工具类
RestTemplate请求调用工具(纯工具类)
原代码(工具类中的自动注入处理)
@Autowired
private RestTemplate restTemplate;
private static RestTemplate rtl;
@PostConstruct
public void initTemplate(){
rtl = restTemplate;
}
报错代码(控制台Description)
Field restTemplate in com.rest_template.utils.RestTemplateUtil required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
解决方法
报错代码显示找不到rest Template对应的Bean,意思就是没被初始化并注入容器
在项目中配置一个配置类,通过两个注解来注入restTemplate的bean到容器
配置类
package com.rest_template.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @ClassDescription: 初始化restTemplate的配置类
* 通过@Configuration和@Bean将创建的RestTemplate注入容器中
* @Author:李白
* @Date:2023/4/3 15:54
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate RestTem(){
return new RestTemplate();
}
}