定义
RestTemplate 是Spring框架提供的基于REST的服务组件,底层对HTTP请求及响应进行了封装,提供了许多访问RETS服务的方法,可简化代码开发
无需额外引入依赖,在启动类添加Bean
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在controller层注入使用
@RestController
@RequestMapping("rest")
public class RestTempleController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public List<Student> findAll(){
//return restTemplate.getForEntity("http://localhost:8010/student/findAll", List.class).getBody();
return restTemplate.getForObject("http://localhost:8010/student/findAll", List.class);
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") Long id){
//return restTemplate.getForEntity("http://localhost:8010/student/findById/{id}", Student.class,id).getBody();
return restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
restTemplate.postForEntity("http://localhost:8010/student/save",student,null).getBody();
}
}