美文网首页
RestTemplate注解Autowired后启动报错

RestTemplate注解Autowired后启动报错

作者: 夜色001 | 来源:发表于2021-09-06 16:44 被阅读0次

新增引用:

@Autowired
    private RestTemplate restTemplate;

启动后报错,

***************************
APPLICATION FAILED TO START
***************************
 
Description:
 
Field restTemplate in com.seco.ad.controller.MobileAdController required a bean of 
type 'org.springframework.web.client.RestTemplate' that could not be found.
 
Action:
 
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

原因:未将RestTemplate纳入Sping容器管理。使用Configuration注解,将RestTemplate实例化,纳入Spring管理后,方可自动注入。

package pro.haichuang.jiudian.config;

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;

/**
 * RestTemplate配置
 * 这是一种JavaConfig的容器配置,用于spring容器的bean收集与注册,并通过参数传递的方式实现依赖注入。
 * "@Configuration"注解标注的配置类,都是spring容器配置类,springboot通过"@EnableAutoConfiguration"
 * 注解将所有标注了"@Configuration"注解的配置类,"一股脑儿"全部注入spring容器中。
 *
 * @author mht
 */
@Configuration
public class RestTemplateConfig {

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

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

相关文章

网友评论

      本文标题:RestTemplate注解Autowired后启动报错

      本文链接:https://www.haomeiwen.com/subject/tbtywltx.html