20

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

@Override
public List<Documents> getDocumentList(@NotNull Integer companyId) {
    Company company = new Company(companyId);
    return this.documentRepository.findByCompany(company);
}

I wanted to use Javax validation constraints to ensure that the companyId being passed in, is not null. But it seems to not have any effect, as I'm able to pass in a null value, and it flows down to the findByCompany call on the repository. I also added @Valid before @NotNull to force validation, but that too didn't do anything.

I could always write a couple of lines to check for a null value, but wanted to use javax.validation annotations to make the code more readable and concise. Is there a way to make the annotations work on method params?

sisanared
  • 4,175
  • 2
  • 27
  • 42

4 Answers4

11

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

import org.springframework.validation.annotation.Validated;
sisanared
  • 4,175
  • 2
  • 27
  • 42
2

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.

Moshe Arad
  • 3,587
  • 4
  • 18
  • 33
0

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.
Michael
  • 41,989
  • 11
  • 82
  • 128
JavaBohne
  • 171
  • 2
  • 4
-6

@NotNull Annotation,

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot hold null value.
Balasubramanian
  • 700
  • 7
  • 26
  • 5
    Downvote as providing some general programming hints inapropriate to the question does not help anyone. And furthermore your second statement is confusing / incomplete (or wrong if meant as written). – Sebastian Jul 26 '18 at 08:35