SpringBoot 注入RestTemplate 我看了一下大都是让我们在启动类里面加一个Bean配置代码如下

    @Autowired
    private RestTemplateBuilder builder;

    public static void main(String[] args) {

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

或者说是加一个

RestTemplateConfig.clss文件,放在启动类同包下,但是这个我没有验证
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }

但是我要说的不是这个

上面的很容易就搜到了,

我说的是关于注入时候回存在的问题

 

我们一般都是将,RestTemplate注入到Service里面,但是如果我们不将RestTemplate注入到Service而是注入到一个工具类,当成一个查询的工具使用的时候,我们就不能使用传统的注入方式

@Autowired
private RestTemplate restTemplate;

这样注入的时候还是会出现空指针的,但是我仔细翻了一下别的博客都没有对这个的解决方式,

实际上我们可以采用下面方式进行注入

 @Resource
    public void setRestTemplate(RestTemplate restTemplate) {
        IDUtil.restTemplate = restTemplate;
    }

这样的话,我们在当成工具类使用的时候也不会出现空指针的异常了.

 public  static  String  getName(){
        if(!isOpenEureka){
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://"+ url+"/getName", String.class);
            return forEntity.getBody();
        }
        return  null;
    }

 

相关文章:

  • 2022-12-23
  • 2021-11-29
  • 2022-02-11
  • 2022-12-23
  • 2022-12-23
  • 2021-08-15
  • 2022-12-23
  • 2022-01-02
猜你喜欢
  • 2021-07-13
  • 2021-10-30
  • 2022-12-23
  • 2021-11-24
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案