스프링
[Spring] RestTemplate 사용법
nan2
2023. 10. 10. 13:29
반응형
1. 애플리케이션 클래스에 RestTemplate을 Bean으로 등록
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
...
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
2. exchange() 메서드로 요청하기
public UserDto getUserByUserId(String userId) {
...
/**
* Using as RestTemplate
*/
ResponseEntity<List<ResponseOrder>> responseOrders =
// exchange(url, 요청메서드 방식, request 할 때 파라미터 데이터 타입, response 할 떄 파라미터 데이터 타입)
restTemplate.exchange(orderUrl,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<ResponseOrder>>() {
});
List<ResponseOrder> orders = responseOrders.getBody();
userDto.setOrders(orders);
return userDto;
}반응형