I am trying to setup basic Auth for my spring boot project. So far, I've done this:
CallAPI.java in com.app.apitool.RESTConsumer package
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 in com.app.apitool.HTTPAuthSetup package
@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;
}
}
Upon running I get the following exception:
APPLICATION FAILED TO START
Description:
Field rest in com.appd.apitool.RESTConsumer.CallAPI required a bean of type 'org.springframework.web.client.RestOperations' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.web.client.RestOperations' in your configuration.
I googled this error and I came across a similar (if not same) issue here and I'm following the solution mentioned here.
The reason I've decided to create a new issue is because I didn't see any solution mentioned in the post where the first link. Also, I'm new to spring-boot framework.
Main App.java in com.app.apitool package:
@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();
}
}
RestOperations
is an interface implemented byRestTemplate
, and you have auto-wired aRestTemplateBuilder
for creatingRestTemplate
objects, so why do you believe you can auto-wireRestOperations
? Use the builder. That's what it's for. --- Then again, you also have aRestTemplate
field with a locally created instance, so why are you needing aRestOperations
? – Andreas Jul 15 '18 at 1:58RestTemplateBuilder
? Why did you believe you needed to wire in aRestOperations
? Why did you create aRestTemplate
directly? The 3 actions seem to all be for the same purpose. What weird tutorial have you been following? Recheck your source material to see how it should be done. – Andreas Jul 15 '18 at 2:03RestTemplateBuilder
, use it to build aRestTemplate
, and then use that to execute a REST call. – Andreas Jul 15 '18 at 2:05