我有以下配置类(用于定义可以自动装配的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.
发生了什么事?
提前致谢
答案 0 :(得分:2)
正如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;
}
}
答案 1 :(得分:0)
配置就像这样:
@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;
}
}