之前生产环境报了一个神奇的错误,接口调用时,入参直接空指针!
模拟一下当时的错误:
入参实体类如下:
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ayton Echo
* @date 2022年01月21日 10:31
*/
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Test {
String oderName;
String orderType;
private String orderTypeWithLabel;
private static final Map<String, String> orderTypeMap = new ConcurrentHashMap<>();
static {
orderTypeMap.put("a", "xx1");
orderTypeMap.put("b", "xx2");
}
public String getOrderTypeWithLabel() {
String label = orderTypeMap.get(this.orderType);
if (StringUtils.isEmpty(label)) {
return this.orderType;
} else {
return this.orderType + "-" + orderTypeMap.get(this.orderType);
}
}
}
执行一段:
public static void main(String[] args) {
Test test = new Test();
test.setOrderType(null);
System.out.println(test);
}
报错:
Exception in thread "main" java.lang.NullPointerException
原因是:
@Data注解中有默认toString方法的重写,展示数据时,默认调用get方法的方式。
所以当你的get方法中有计算或者调用时,而你的属性值是null,就会报错。
上面例子中getOrderTypeWithLabel() 方法中的 this.orderType 是null,所以走get方法时,出错了。
解决办法有两个,自行选择即可:
1、修改getOrderTypeWithLabel() 方法的逻辑。
public String getOrderTypeWithLabel(){
if(this.orderType != null){
String label = orderTypeMap.get(this.orderType);
if(StringUtils.isEmpty(label)){
return this.orderType;
}else{
return this.orderType+"-"+orderTypeMap.get(this.orderType);
}
}else {
return null;
}
}
2、实体类添加 @ToString(doNotUseGetters = true) 注解
这个注解的意思是展示数据时,不会默认调用get方法了,而是直接取属性的值。(默认是false)
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ayton Echo
* @date 2022年01月21日 10:31
*/
@Data
@ToString(doNotUseGetters = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Test {
String oderName;
String orderType;
private String orderTypeWithLabel;
private static final Map<String, String> orderTypeMap = new ConcurrentHashMap<>();
static {
orderTypeMap.put("a", "xx1");
orderTypeMap.put("b", "xx2");
}
public String getOrderTypeWithLabel() {
String label = orderTypeMap.get(this.orderType);
if (StringUtils.isEmpty(label)) {
return this.orderType;
} else {
return this.orderType + "-" + orderTypeMap.get(this.orderType);
}
}
}
执行后:
Test(oderName=null, orderType=null, orderTypeWithLabel=null)
至此,问题解决,特此记录。