当前位置: 首页 > 面试题库 >

如何使用注释自动连接RestTemplate

狄宜然
2023-03-14
问题内容

当我尝试自动装配Spring RestTemplate时,出现以下错误:

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

在注释驱动的环境中使用Spring 4。

我的调度程序servlet的配置如下:

<context:component-scan base-package="in.myproject" />
<mvc:default-servlet-handler />    
<mvc:annotation-driven />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

我尝试自动连接RestTemplate的类如下:

@Service("httpService")
public class HttpServiceImpl implements HttpService {

@Autowired
private RestTemplate restTemplate;

@Override
public void sendUserId(String userId){

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("userId", userId);
    map.add("secretKey", "kbhyutu7576465duyfy");

    restTemplate.postForObject("http://localhost:8081/api/user", map, null);


    }
}

问题答案:

如果RestTemplate未定义错误,则会看到错误

考虑在配置中定义类型为“ org.springframework.web.client.RestTemplate”的bean。

要么

找不到类型为[org.springframework.web.client.RestTemplate]的合格Bean

如何定义RestTemplate通孔注释

取决于你使用的技术以及哪种版本会影响你RestTemplate在@Configuration课堂上定义a 的方式。

没有Spring Boot的Spring> = 4

只需定义一个@Bean

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

Spring Boot <= 1.3

无需定义一个,Spring Boot会自动为你定义一个。

Spring Boot >= 1.4

Spring Boot不再自动定义一个RestTemplate,而是定义一个RestTemplateBuilder允许你对RestTemplate创建的对象进行更多控制的控件。你可以RestTemplateBuilder在@Bean方法中注入作为参数来创建一个RestTemplate

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here
   return builder.build();
}

在课堂上使用它

@Autowired
private RestTemplate restTemplate;

or

@Inject
private RestTemplate restTemplate;


 类似资料:
  • 在Springs的最新版本中,我们可以使用注释作为自动连接bean。这将使用bean的类型(或构造函数,如果应用于它的话)自动连接bean。有什么方法可以使用基于bean名称的注释吗?我们在Spring的XML文件中没有注释autowire=“byName”?

  • 我正在学习SpringBoot,在参考文档中有一个例子,我有一个问题。文件的以下部分提到 6.使用@SpringBootApplication注释 可以使用单个@SpringBootApplication注释来启用这三个功能,即: @EnableAutoConfiguration:启用Spring Boot的自动配置机制 @ComponentScan:在应用程序所在的包上启用@Component扫

  • 和和注释之间有什么区别? 我们应该在什么时候使用它们每一个?

  • 我在应用程序中配置了Spring cloud sleuth(以及zipkin)。我有一个控制器,它调用服务,然后调用存储库,最后调用数据库。 设置工作正常,Sleuth正在生成spans id,它在zipkin中也可见。我想尝试跨多个内部bean和方法创建spans。我遇到了使用注释管理跨度。这似乎不起作用。 当我使用这里提到的任何注释时,如NewSpan或ContinueSpan,自动连接停止工

  • 我正在运行Spring Boot2.0.1和JUnit5。我正在尝试在集成测试中获取端口。但是,端口值始终为零。我不确定是什么引起的。我尝试将web环境枚举更改为随机端口,但似乎没有任何工作。 下面是pom(注意:仅显示依赖项) 应用程序.属性

  • 我有一个json,它在一个领域模型中通过annotaion@SerializedName使用gson进行转换。 但有时在json中,有一个未知的键,我想将它编为字符串。 我在列表woList=gson.fromjson(parentArray,new typeToken>(){}.getType())上序列化了它;