- 依赖:lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
项目common结构:
CommonResponse写法
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import java.io.Serializable;
@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResponse<T> implements Serializable {
private int status;
private String msg;
private T data;
private CommonResponse(int status){
this.status=status;
}
private CommonResponse(int status,String msg){
this.status=status;
this.msg=msg;
}
private CommonResponse(int status,String msg,T data){
this.status=status;
this.msg=msg;
this.data=data;
}
private CommonResponse(int status,T data){
this.status=status;
this.data=data;
}
@JsonIgnore
public boolean isSuccess(){
return this.status == ResponseCode.SUCCESS.getCode();
}
public static <T> CommonResponse <T> createForSuccess(){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> CommonResponse <T> createForSuccess(T data){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> CommonResponse <T> createForSuccessMessage(String msg){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> CommonResponse <T> createForSuccess(String msg,T data){
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> CommonResponse <T> createForError(){
return new CommonResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDescription());
}
public static <T> CommonResponse <T> createForError(String msg){
return new CommonResponse<T>(ResponseCode.ERROR.getCode(),msg);
}
public static <T> CommonResponse <T> createForError(int code,String msg){
return new CommonResponse<T>(code,msg);
}
}
ResponseCode(枚举)的写法
import lombok.Getter;
@Getter
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),
ERROR(1,"ERROR"),
NEED_LOGIN(10,"NEED_LOGIN"),
ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");
private final int code;
private final String description;
ResponseCode(int code,String description){
this.code=code;
this.description = description;
}
}