【问题标题】:Spring's RestTemplate bean errorSpring的RestTemplate bean错误
【发布时间】:2018-03-27 09:52:34
【问题描述】:

我有以下配置类(用于定义可以自动装配的 RestTemplate bean):

@Configuration
public class RestTemplateConfiguration {

    @Bean
    RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

然后我收到以下错误:

 The class org.springframework.web.client.RestTemplate used in the bean named getRestTemplate is not allowed to use it.

发生了什么事?

提前致谢

【问题讨论】:

  • 你能显示完整的错误日志吗?顺便说一句,它和我一起工作
  • 为什么 bean 不公开?
  • 你试过这个定义吗:@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) {return builder.build(); }
  • 是的,它也不起作用
  • 当您使用SpringBoot时,您可以在声明@SpringBootApplication注释的类中定义@Bean(name = "restTemplate") public RestTemplate restTemplate(RestTemplateBuilder builder) { RestTemplate REST_TEMPLATE = builder.build(); return REST_TEMPLATE; }

标签: spring spring-mvc spring-boot resttemplate


【解决方案1】:

正如 Amit K Bist 所说,在具有符号 @SprinBootApplication 的类中,您应该定义一个类型的 bean。

org.springframework.web.client.RestTemplate

我遇到了同样的问题,但是这个解决了,希望对你有帮助

    package [package];

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableCaching
@ComponentScan({ [package/s] })
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean(name = "restTemplate") 
    public RestTemplate restTemplate(RestTemplateBuilder builder) { 
        RestTemplate REST_TEMPLATE = builder.build(); return REST_TEMPLATE; 
    }
}

【讨论】:

    【解决方案2】:

    像这样配置:

    @Configuration
        @ComponentScan(*YOUR PACKAGE NAME*)
        public class AppConfig {
    
            @Bean
            RestTemplate restTemplate() {
                RestTemplate restTemplate = new RestTemplate();
                MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
                converter.setObjectMapper(new ObjectMapper());
                restTemplate.getMessageConverters().add(converter);
                return restTemplate;
            }
        }
    

    【讨论】:

    • 这有什么不同? @ComponentScan 为什么要解决任何问题?
    • 好吧,你复制+粘贴了这个。我的问题是它如何解决当前的问题。 @ComponentScan 对初始化 RestTemplate bean 没有任何作用。
    • 感谢您提供信息
    猜你喜欢
    • 2011-12-26
    • 2016-08-22
    • 2015-04-01
    • 1970-01-01
    • 2019-05-19
    • 2017-08-15
    • 2020-06-20
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多