Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javax@NotNull注释用法_Java_Spring_Spring Boot - Fatal编程技术网

Javax@NotNull注释用法

Javax@NotNull注释用法,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个简单的方法来获取给定公司id的文档列表。方法如下: @Override public List<Documents> getDocumentList(@NotNull Integer companyId) { Company company = new Company(companyId); return this.documentRepository.findByCompany(company); } @覆盖 公共列表getDocumentList(@No

我有一个简单的方法来获取给定
公司id
的文档列表。方法如下:

@Override
public List<Documents> getDocumentList(@NotNull Integer companyId) {
    Company company = new Company(companyId);
    return this.documentRepository.findByCompany(company);
}
@覆盖
公共列表getDocumentList(@NotNull Integer companyId){
公司=新公司(公司ID);
返回此.documentRepository.findByCompany(公司);
}
我想使用Javax验证约束来确保传入的
companyId
不是
null
。但它似乎没有任何效果,因为我能够传入一个
null
值,它向下流到存储库上的
findByCompany
调用。我还在
@NotNull
之前添加了
@Valid
以强制验证,但这也没有起到任何作用


我总是可以写几行代码来检查
null
值,但我想使用
javax.validation
注释使代码更具可读性和简洁性。有没有办法让注释在方法参数上工作?

来自Java EE 6教程:

Bean验证模型由以下形式的约束支持 放置在JavaBeans的字段、方法或类上的注释 组件如托管bean

您应该对与声明的bean相关的字段进行验证,如下所示:

@Entity
@Table(name="users")
public class BackgammonUser {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long userId;

    @Column(name="username")
    @NotBlank
    private String userName;

    @NotBlank
    private String password;

    @NotNull
    private Boolean enabled;
}
双陆棋用户被认为是一个bean。

@NotNull注释

  • 方法不应返回null
  • 变量(如字段、局部变量和参数)不能包含空值

  • 要激活参数验证,只需使用
    @Validated

    import org.springframework.validation.annotation.Validated;
    

    如果
    @用方法注入一个类,它将按预期工作

    @Stateless
    public class MyBean{ 
        @Inject
        TestClass test;
    }
    

    public class TestClass {
        public List<Documents> getDocumentList(@NotNull Integer companyId)
        {
            //...
        }
    }
    

    我知道这一点。我不想为单个参数创建bean,这是一个限制。您也可以在JavaEE6教程中查找它,谢谢。我想,我必须手动编写空检查:)我们可以在实体类上使用@NotNull注释,而不是检查每个变量吗?如果我没有使用springYou可以使用projectlombok(lombok.NonNull)中的@NonNull添加更多注释会对性能产生任何影响吗?在调用实际方法之前再添加一层?@Validated的影响对noneDownvote来说微不足道,因为提供一些不适合该问题的通用编程提示对任何人都没有帮助。此外,你的第二个陈述令人困惑/不完整(如果是书面的话,也可能是错误的)。
    WFLYEJB0034: EJB Invocation failed on component MyBean for method ...:
    javax.ejb.EJBException: javax.validation.ConstraintViolationException:
    1 constraint violation(s) occurred during method validation.