【发布时间】:2018-12-22 23:35:05
【问题描述】:
我正在尝试为我的 Spring Boot 项目设置基本身份验证。到目前为止,我已经这样做了:
com.app.apitool.RESTConsumer 包中的CallAPI.java
public class CallAPI {
RestTemplate restTemplate = new RestTemplate();
@Autowired
RestTemplateBuilder restTemplateBuilderObj;
@Autowired
BasicAuthSetup basicAuthObj;
@Autowired
RestOperations rest;
String endpointURL = "";
public String pingAPi() {
HttpEntity<String> request = new HttpEntity<String>(basicAuthObj.getHeaders());
ResponseEntity<String> response = rest.exchange(endpointURL, HttpMethod.GET, request, String.class);
System.out.println(response.getBody());
return response.getBody();
}
}
BasicAuthSetup.java 在 com.app.apitool.HTTPAuthSetup 包中
@Component
public class BasicAuthSetup {
private String plainCreds = "id@account1:password";
private String base64Creds = Base64.getEncoder().encodeToString(plainCreds.getBytes());
@Bean
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic" + base64Creds);
System.out.println("Auth created: "+headers);
return headers;
}
}
运行时出现以下异常:
应用程序启动失败
说明:
com.appd.apitool.RESTConsumer.CallAPI 中的字段 rest 需要一个 bean 输入 'org.springframework.web.client.RestOperations' 不能 找到了。
行动:
考虑定义一个 bean 类型 'org.springframework.web.client.RestOperations' 在你的配置中。
我用谷歌搜索了这个错误,我遇到了一个类似(如果不相同)的问题here,我正在遵循here 提到的解决方案。
我决定创建一个新问题的原因是因为我没有看到第一个链接所在的帖子中提到的任何解决方案。另外,我是 spring-boot 框架的新手。
com.app.apitool 包中的主要 App.java:
@SpringBootApplication
@RestController
public class App {
private static final Logger log = org.slf4j.LoggerFactory.getLogger(App.class);
@Autowired
private CallAPI callAPIobj;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@RequestMapping("/api")
public String testAPI() {
return callAPIobj.pingAPi();
}
}
【问题讨论】:
-
这里缺少很多上下文。您如何尝试将所有这些连接在一起? Java配置? XML 配置?你能展示一些吗?此外,显示整个类,包括包定义等。
-
@EricGreen 我没有任何配置文件,因为这是一个非常简单的基本结构。我以前从未使用过 spring 框架。我已经在上面添加了我的主类。
-
RestOperations是由RestTemplate实现的接口,并且您已经为创建RestTemplate对象自动连接了一个RestTemplateBuilder,那么为什么你认为你可以自动连接RestOperations?使用生成器。这就是它的用途。 --- 再说一次,您也有一个带有本地创建实例的RestTemplate字段,那么为什么需要RestOperations? -
@user2607744 你为什么在
RestTemplateBuilder中电汇?为什么你认为你需要在RestOperations中电汇?为什么直接创建RestTemplate?这三个动作似乎都是为了同一个目的。你一直在关注什么奇怪的教程?重新检查您的源材料以了解它应该如何完成。 -
或者只是阅读文档,即Spring Boot 参考指南,33. Calling REST Services with RestTemplate 部分,它表明您连接到
RestTemplateBuilder,用它来构建一个RestTemplate,然后用它来执行一个REST调用。
标签: java rest api spring-boot