一:类及类之间关系
本文一共出现了五个类。
1:自定义注解 EnumValidAnnotation
2:操作工具类 EnumValidtor
3:枚举类 OrganizationStatusEnum
4:VO类型实体类 OrganizationAbstractVO
5:controller层 OrganizationManageController
类之间关系如下
EnumValidAnnotation与EnumValidtor之间有紧耦合。这点非常不好,时间关系没有很好的拆解开。所以大家在使用的时候请一定注意。
枚举类的值作为vo类型实体的status字段的取值范围
实体作为controller某方法的入参
二:代码
2.1:自定义注解 EnumValidAnnotation
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* @author :dark
* @title :EnumValidAnnotation
* @description :配合@Validate一起使用的、用来校验枚举的注解
* @date :2020年3月17日
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {EnumValidtor.class})
@Documented
public @interface EnumValidAnnotation {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<?>[] target() default {};
}
2.2:操作工具类 EnumValidtor
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author :dark
* @title :EnumValidtor
* @description :配合注解 @EnumValidAnnotation验证每个枚举值是否符合枚举类的工具类
* @date :2020年3月17日
*/
public class EnumValidtor implements ConstraintValidator<EnumValidAnnotation,String> {
/**
* 枚举类
*/
Class<?>[] cls ;
@Override
public void initialize(EnumValidAnnotation enumValidAnnotation) {
cls = enumValidAnnotation.target();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(cls.length>0 ){
for (Class<?> cl : cls
) {
try {
if(cl.isEnum()){
/**
* 枚举类验证
*/
Object[] objs = cl.getEnumConstants();
Method method = cl.getMethod("getValue");
for (Object obj : objs
) {
Object code = method.invoke(obj,null);
if(value.equals(code.toString())){
return true;
}
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} else {
return true;
}
return false;
}
}
2.3:枚举类 OrganizationStatusEnum
public enum OrganizationStatusEnum {
NEWADD("新增","1"),
CANCEL("注销","2"),
;
private OrganizationStatusEnum(String key,String value) {
this.key = key;
this.value = value;
}
private String value;
private String key;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public static OrganizationStatusEnum getByValue(String val) {
OrganizationStatusEnum[] vals = values();
for (OrganizationStatusEnum v : vals) {
if (v.getValue().equals( val)) {
return v;
}
}
return null;
}
}
2.4:实体类 OrganizationAbstractVO
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @author :dark
* @title :OrganizationAbstractVO
* @date :2020年2月5日
*/
@ApiModel(description="OrganizationAbstractVO", value="OrganizationAbstractVO")
public class OrganizationAbstractVO implements Serializable{
private static final long serialVersionUID = 1L;
/**
* id
*/
@ApiModelProperty(name="id", value="id")
private Long id;
/**
* org_name
*/
@ApiModelProperty(name="name", value="组织机构名称")
@NotBlank(message = "name不能为空")
@Length(max = 40 ,message = "长度在40字符以内")
private String name;
/**
* org_status
*/
@ApiModelProperty(name="status", value="机构状态。1:正常;2:注销")
@NotBlank(message = "status不能为空")
@EnumValidAnnotation(message = "枚举类型值输入错误", target = OrganizationStatusEnum.class )
private String status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
2.5:controller层
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* @author :dark
* @title :OrganizationManageController
* @date :2020年1月7日
*/
@Controller
@RequestMapping("/organization")
@Api(value = "组织机构管理Controller", tags = {"组织机构管理"})
@Validated
public class OrganizationManageController {
/**
* @description :新增组织机构
* @param :所有的param
*/
@ApiOperation(value = "", notes = "新增组织机构", httpMethod = "POST")
@ResponseBody
@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Object orgManageSave(@RequestBody @Validated() OrganizationAbstractVO vo
, HttpServletRequest request, HttpServletResponse response) {
CreditOrg creditOrg = null;
return null;
}
三:使用与效果
我们把自定义的注解,加到 OrganizationAbstractVO 类的 status属性上,效果如下
@EnumValidAnnotation(message = "枚举类型值输入错误", target = OrganizationStatusEnum.class )
private String status;
这样,当对这个实体的status参数传输的值不在枚举值的范围内,就会报错。
零:参考资料
因为一半以上的内容都是借鉴了人家的东西,因此把人家的连接放在最上面。传送门