软件编程
位置:首页>> 软件编程>> java编程>> 解决RestTemplate加@Autowired注入不了的问题

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

作者:梦想注定是孤独的旅行  发布时间:2022-07-14 03:00:48 

标签:RestTemplate,@Autowired,注入

RestTemplate加@Autowired注入不了

1、在启动类加入

如图箭头所示代码:

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

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

完美解决

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

SpringBoot 如何注入RestTemplate

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

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


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;
  }
}

之后使用


@Autowired
private RestTemplate restTemplate;

直接正常使用就可以


String url = "http://localhost:8080/findById?id=1";//请求的地址
String request = restTemplate.getForObject(url, String.class);

来源:https://blog.csdn.net/qq_40667143/article/details/83444822

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com