当前位置: 代码迷 >> 综合 >> service中@NotNull的使用
  详细解决方案

service中@NotNull的使用

热度:76   发布时间:2024-02-21 17:48:30.0

 @Validated和@NotNull加到什么上面,接口还是实现?

简化代码

/*** 测试接口* @author edc*/
public interface TestService {/*** 测试notnull* @param str* @return*/String testOne(@NotNull String str);}/*** @Description 测试notnull* @Author edward.coo* @Date 2020/9/23 10:47* @Version 1.0*/
@Service
@Validated
public class TestServiceImpl implements TestService {@Overridepublic String testOne(@NotNull String str) {return "参数:"+str;}
}

 

场景结果:

场景

TestService

TestServiceImpl

结果

结果测试图

1

@Validated √

@NotNull √

@Validated √

@NotNull √

可以校验

javax.validation.ConstraintViolationException: testOne.str: 不能为null

2

@Validated √

@NotNull √

@Validated ×

@NotNull ×

可以校验

javax.validation.ConstraintViolationException: testOne.str: 不能为null

3

@Validated √

@NotNull √

@Validated ×

@NotNull √

可以校验

javax.validation.ConstraintViolationException: testOne.str: 不能为null

4

@Validated √

@NotNull √

@Validated √

@NotNull ×

可以校验

javax.validation.ConstraintViolationException: testOne.str: 不能为null

5

@Validated √

@NotNull ×

@Validated √

@NotNull √

不行

javax.validation.ConstraintDeclarationException: HV000151: A method overriding another method must not redefine the parameter constraint configuration, but method TestServiceImpl#testOne(String) redefines the configuration of TestService#testOne(String)

6

@Validated √

@NotNull ×

@Validated ×

@NotNull √

不行

javax.validation.ConstraintDeclarationException: HV000151: A method overriding another method must not redefine the parameter constraint configuration, but method TestServiceImpl#testOne(String) redefines the configuration of TestService#testOne(String)

7

@Validated ×

@NotNull √

@Validated √

@NotNull √

可以校验

javax.validation.ConstraintViolationException: testOne.str: 不能为null

8

@Validated ×

@NotNull √

@Validated ×

@NotNull ×

不行

程序正常执行,校验不生效

9

@Validated ×

@NotNull √

@Validated ×

@NotNull √

不行

程序正常执行,校验不生效

10

建议

@Validated ×

@NotNull √

@Validated √

@NotNull ×

可以校验

javax.validation.ConstraintViolationException: testOne.str: 不能为null

11

@Validated ×

@NotNull ×

@Validated √

@NotNull √

不行

javax.validation.ConstraintDeclarationException: HV000151: A method overriding another method must not redefine the parameter constraint configuration, but method TestServiceImpl#testOne(String) redefines the configuration of TestService#testOne(String)

12

@Validated ×

@NotNull ×

@Validated ×

@NotNull √

不行

程序正常执行,校验不生效

 

import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;

总结:

1. @Validated 与@NotNull同时存在才生效

2. @NotNull需要在接口中定义才生效

3. @Validated可以在接口中定义,也可以在实现类中定义,建议在实现类中定义,因为同一个接口的多个实现校验需求存在差异

4. 校验生效的情况下,抛出的不是空指针异常,而是javax.validation.ConstraintViolationException

 

  相关解决方案