背景是我在用一个restTemplate作为微服务的协议写了一个简单的查和增,查的话能出来,增的话就会报上面的错。附上代码:
服务者:
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
// http://localhost:8001/payment/create?serial=aaa页面上这样写,要在postman上面写
@PostMapping("/payment/create")
public CommonResult create(@RequestBody Payment payment){
int result=paymentService.create(payment);
if (result>0){
return new CommonResult(200,"success",result);
}else {
return new CommonResult(444,"flase",null);
}
}
@GetMapping(value = "/payment/get/{id}")
/* 请求值路径这样写的时候value = "/payment/get"
http://localhost:8001/payment/get?id=1 页面上这样写,参数是@Param
如果是value = "/payment/get/{id}",页面上http://localhost:8001/payment/get/1,但是参数要用
@PathVariable来表示*/
public CommonResult getPaymentById(@PathVariable("id")Integer id){
Payment payment=paymentService.getPaymentById(id);
if (payment!=null){
return new CommonResult(200,"success",payment);
}else {
return new CommonResult(444,"flase",null);
}
}
}
消费者:
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL="http://localhost:8001";
@Resource
private RestTemplate restTemplate;
// @Resource代表着autowire和quelifier
// 一般读操作用get,写操作用postObject
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
/*postForObject第一个参数,是地址,找到提供者。第二个参数是带参过去。第三个参数是返回的值,返回的是一个
CommonResult类,因为是客户端,所以都用get方法提交http://localhost/consumer/payment/create?serial=222*/
@GetMapping("consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Integer id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
@Configuration
public class applicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
这里是我的消费者的封装类
public class Payment implements Serializable {
private Integer id;
private String serial;/*支付流水号*/
@Override
public String toString() {
return "Payment{" +
"id=" + id +
", serial='" + serial + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public Payment(Integer id, String serial) {
this.id = id;
this.serial = serial;
}
public Payment() {
}
}
然后运行:会报错,后来发现是因为我的消费者的封装类的id我定义的是Integer的类型,但是做get,set方法的时候,没注意改,写成了int类型,这样会导致你使用get方法的时候,得不到封装类,自然也会说明你的代码id空指针。把int改成integer问题解决。