我想把一个由另一个对象组成的对象作为一个属性来传递,如何实现?
例如
类
public class CustomerProduct{
private int customerId;
private String customerName;
private Product product;
//Constructors and getters setters
}
Product p1 = new Product(with required args);
CustomerProduct obj = new CustomerProduct(1,"John",p1);
现在我需要把obj作为对象传给rest API post方法[这里的rest API是由spring boot实现的]。
Response response1 =client.target(endPointUrl).request().post(Entity.json(obj));
在此方法的帮助下,休息API将只接收customerId和customerName,而Product对象将以null形式获取。
rest API方法的示例代码
@PostMapping("/customer-product")
public void sampleControllerMethod(@RequestBody CUstomerProductDTO customerProductDTO){
customerProductService.methodA(customerProductDTO);
}
如何解决这个问题?
在这里,我解决这个问题的方法是将产品类中需要的属性作为CustomerProduct类中的属性。
举个例子,在CustomerProduct类中,我使用的是product类中的属性。
public class CustomerProduct{
private int customerId;
private String customerName;
//Using the attributes in Product class as attributes in CustomerProduct class
private String productName;
private String productPrice;
//Likewise I used product object attributes inside the CustomerProduct class
//Overloaded constructors and getters setters
}
然后我把CustomerProduct的对象作为一个单一的对象传递给Rest API的post方法 使用jax-rs,如下所示
CustomerProduct obj = new CustomerProduct(args);
Response response1 =client.target(endPointUrl).request().post(Entity.json(obj));