Javax @NotNull annotation usage

后端 未结 4 378
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 12:49

I have a simple method to get a list of documents for a given companyId. Here is the method:

@Override
public List getDocumentL         


        
相关标签:
4条回答
  • 2021-01-17 13:17

    @NotNull Annotation,

    1. A method should not return null.
    2. A variable (like fields, local variables, and parameters) cannot hold null value.
    0 讨论(0)
  • 2021-01-17 13:18

    If you @Inject a class with your method, its working as expected.

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

    and

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

    ConstraintViolationException when you call your method with null parameter:

    WFLYEJB0034: EJB Invocation failed on component MyBean for method ...:
    javax.ejb.EJBException: javax.validation.ConstraintViolationException:
    1 constraint violation(s) occurred during method validation.
    
    0 讨论(0)
  • 2021-01-17 13:24

    To activate parameter validation, simply annotate the class with @Validated

    import org.springframework.validation.annotation.Validated;
    
    0 讨论(0)
  • 2021-01-17 13:41

    From The Java EE 6 Tutorial:

    The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean.

    You should place your validation of a field related to a declared bean, something like this:

    @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;
    }
    

    The BackgammonUser is considered to be a bean.

    0 讨论(0)
提交回复
热议问题