1.描述

SpringBoot项目中RestTemplate无法通过@Autowired注入的问题

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

2.情景

我再若依框架设计到文件的上传,有一部分需要涉及到使用外部Url获取数据的部分,结果独立出来之后,发现RestTemplate无法注入

3.分析

在已经import相关包的前提下只能说明:装配失败

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

意思就是虽然引入了RestTemplate包,但是@Autowired注解无法将其注入到Spring容器当中(Auto wired无法找到RestTemplate的Bean),但是明明之前项目是可以使用的,查阅一些相同的问题后我发现了:

springboot是无法自动注入RestTemplate 的,但是springcloud就可以自动注入,因此将其独立出来之后不能够简单照旧;需要我们在springboot配置类中注入RestTemplate,也就是在启动类加上RestTemplate的Bean

4.解决

修改启动入口文件

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication
{
    @Autowired
    //RestTemplateBuilder
    private RestTemplateBuilder builder;
    // 使用RestTemplateBuilder来实例化RestTemplate对象,spring默认已经注入了RestTemplateBuilder实例
    @Bean
    public RestTemplate restTemplate() {
        return builder.build();
    }

    public static void main(String[] args)
    {
        // System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(RuoYiApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙  若依启动成功   ლ(´ڡ`ლ)゙  \n" +
                " .-------.       ____     __        \n" +
                " |  _ _   \\      \\   \\   /  /    \n" +
                " | ( ' )  |       \\  _. /  '       \n" +
                " |(_ o _) /        _( )_ .'         \n" +
                " | (_,_).' __  ___(_ o _)'          \n" +
                " |  |\\ \\  |  ||   |(_,_)'         \n" +
                " |  | \\ `'   /|   `-'  /           \n" +
                " |  |  \\    /  \\      /           \n" +
                " ''-'   `'-'    `-..-'              ");
    }
}