【问题标题】:Required a bean of type 'org.springframework.web.client.RestOperations' that could not be found需要一个找不到的“org.springframework.web.client.RestOperations”类型的bean
【发布时间】:2018-06-26 01:54:40
【问题描述】:

嗨,我有这个项目在 Spring Boot 上运行。当我尝试运行时,它给了我以下错误:

说明:

com.mycompany.microservice.myproject.bot.controller.BotCommandController 中的字段 clientCredentialsApi 需要找不到类型为“org.springframework.web.client.RestOperations”的 bean。

行动:

考虑在你的配置中定义一个“org.springframework.web.client.RestOperations”类型的bean。

这是我的代码:

Application.java

package com.mycompany.microservice.myproject
//some imports

@SpringBootApplication`
@ComponentScan(basePackages = "com.mycompany.*")
public class Application {

public static void main(String[] args) {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

这里是控制器:

BotCommandController.java
package com.mycompany.microservice.myproject.bot.controller;
//some imports

@RestController
@RequestMapping("/bot-command")
public class BotCommandController {

@Autowired
private RestOperations clientCredentialsApi;

@RequestMapping(value = "/sraix", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String sraixCommand(@RequestParam(name = "input", required = false) final String input,@RequestParam(name = "cs", required = false) final String cs) throws Exception {

    final UserApiObject userApiObject = clientCredentialsApi.getForObject(env.getProperty("gms.location") + "/rest/user/" + userId, UserApiObject.class);

    return userApiObject.getRole();

}

【问题讨论】:

  • 你的RestOperations 的代码是什么?尝试在您的班级添加@Service@Component。希望对您有所帮助。
  • 我更新了代码
  • 需要添加RestOperations的代码

标签: java spring spring-boot


【解决方案1】:

您正在尝试自动装配您没有定义或实现的 bean。 RestOperations 是一个接口,必须实现。

@Autowired
private RestOperations clientCredentialsApi;

Spring 正在查找带有 @Bean 或 @Component 或 @Service 注释的类以注入它们的引用。在您的情况下,您没有定义 bean RestOperations 并且 Spring 无法将其注入 BotCommandController。

类似这样的:

@Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthorization("user", "password").build();
}

【讨论】:

  • 和我的例子类似的配置里有@Bean吗?
  • 没有.. 实际上它在其他代码上工作。我只是复制代码并将其放入微服务中。
  • 尝试搜索在您的应用程序中实现 RestOperations 的类或返回它的方法。
猜你喜欢
  • 1970-01-01
  • 2018-02-05
  • 2017-09-17
  • 2020-07-06
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
相关资源
最近更新 更多