好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解决RestTemplate加@Autowired注入不了的问题

RestTemplate加@Autowired注入不了

1、在启动类加入

如图箭头所示代码:

然后在进行@Autowired发现不报错了。

完美解决

SpringBoot 如何注入RestTemplate

创建一个文件夹 ,我这边习惯于创建config文件夹

将下面的一段代码放到里面

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import org.springframework.boot.web.client.RestTemplateBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import org.springframework.web.client.RestTemplate;

 

@Configuration

public class RedisConfig {

    @Bean

    public RestTemplate restTemplate(RestTemplateBuilder builder) {

       RestTemplate restTemplate = builder.build();

       restTemplate.getMessageConverters().add( new MappingJackson2HttpMessageConverter());

       return restTemplate;

    }

}

之后使用

?

1

2

@Autowired

private RestTemplate restTemplate;

直接正常使用就可以

?

1

2

String url = "http://localhost:8080/findById?id=1" ;//请求的地址

String request = restTemplate.getForObject(url, String. class );

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_40667143/article/details/83444822

查看更多关于解决RestTemplate加@Autowired注入不了的问题的详细内容...

  阅读:11次