如何在springboot中使用rest模板保存新对象

时间:2018-12-16 13:22:59

标签: java mysql eclipse spring-boot

我有两个拖曳应用程序的学生和两个拖曳端口8081saveStudent() ... StudentDao.save(); 的动作。在第一个应用程序中,我有一张桌子,并且有一种保存学生的方法。但是问题是如何从此方法发送此已保存的对象到其他应用程序,并将其保存在第二个应用程序的表中。一个以上的应用程序之间有休息吗?

第一个应用程序中的方法:

save Income() ... 

secont应用程序中的方法:

{{1}}

1 个答案:

答案 0 :(得分:0)

第一个应用

@RestController
@RequestMapping("/firstApp")
public class FirstAppController{

 @Autowired
 private StudentRepository studentRepository;

 private RestTemplate restTemplate =new RestTemplate();

@PostMapping
public ResponseEntity<String> save(@RequestBody Student student){
  Student savedStudent = studentRepository.saveAndFlush(student);
  //set your headers
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);

  //set your entity to send
  HttpEntity entity = new HttpEntity(savedStudent ,headers);
  // send it!
  return restTemplate.exchange("http://localhost:8081/secondeApp", HttpMethod.POST, entity, String.class);
 }

}

第一个服务的访问URL: [POST]: http;//localhost:8080/firstApp

第二个应用:

    @RestController
    @RequestMapping("/secondeApp")
    public class SecondeAppController{

     @Autowired
     private StudentRepository studentRepository;

    @PostMapping(consumes=MediaType.APPLICATION_JSON)
    public void save(@RequestBody Student student){
      studentRepository.saveAndFlush(student);
     }

    }