Consider defining a bean of type ‘org.springframework.web.client.RestTemplate‘ in your configuration

作者 : admin 本文共1386个字,预计阅读时间需要4分钟 发布时间: 2024-06-16 共1人阅读

      在springcloud开发中,当我们将RestTemplate通过@Autowired注解注入到一个类中,启动服务报错。

springboot1.3版本中会默认提供一个RestTemplate的实例Bean,当在springboot1.4以及以后的版本中,需要手动创建一个RestTemplate的配置:

package com.angel.restTemplate;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Author
 * @Date 2024/3/6 11:14
 * @Version 1.0
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }
}

   这样,我们再在类中通过注解@Autowired使用TestTemplate的时候就不会报错了。或者@Resource也行,如下:

    @Resource
    private RestTemplate restTemplate;
    /**
     * 调用接口地址
     *
     * @param url
     * @param requestJson
     * @param method
     * @return
     */
    private String requestUamData(String url, String requestJson, HttpMethod method) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity entity = null;
        if (method != HttpMethod.GET) {
            entity = new HttpEntity(requestJson, headers);
        }
        ResponseEntity response = restTemplate.exchange(url, method, entity, String.class);
        String str = response.getBody();
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return str;
    }

 当我们在idea中编码时,使用@Autowired注解时,被注解的属性没有被检测到时会出现红叉错误。解决办法就是:File->Settings->Editor->Inspectons->Spring Core->Code->Autowiring for Bean Class->Severity->调整级别Error为Warning,最后apply,问题解决。

本站无任何商业行为
个人在线分享 » Consider defining a bean of type ‘org.springframework.web.client.RestTemplate‘ in your configuration
E-->