Search code examples
javaspringvalidationkarafblueprint

in Java, best way to validate objects with properties annotated with @NonNull


I'm implementing an API gateway in Java, where the request object has lots of fields and subobjects. There are numerous properties that are required (should not be null) and some that are optional.

The code runs in Karaf and is using Blueprint, so some Spring-based mechanisms are possible, but we're not using much from Spring right now (although I'm familiar with the various Spring frameworks).

I'm aware of the Eclipse @NonNull annotation, and I can add that annotation to getter methods that need to return a non-null value.

What I'd like to be able to do is run a reusable method on the request object that will determine if there are any constraint violations and return a human-readable error message (or something else).

There seem to be various ways to do this, but I'm not sure what framework strategy makes sense in my situation. For instance, there is commons-validator, but that seems like it's specific to web page forms. I also saw some documentation for a hibernate validator, but that seems like it wouldn't apply here.


Solution

  • you can use oracle Validation API JSR-303, it is independent framework which can be use in web-based and none web-based applications, Hibernate provides implementation for that JSR-303. you can include the dependencies as follow in you pom.xml file

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    

    and the implementation

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator-annotation-processor</artifactId>
        <version>5.2.1.Final</version>
    </dependency>
    

    in you bean object you can use annotation like @NotEmpty, @NotNull,@Range .... also you can configure each annotation as you like ,for example you can add custom message to @NotNull annotation like

    @NotNull(message = "First Name cannot be null")
    private String firstName;
    

    for validation to work just annotate the entity with @Valid and add another parameter to the controller method of type BindingResult

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public String addUser(@Valid User user, BindingResult result) {
    
            if (result.hasErrors()) {
                return "errorPage";
            } else {
                return "Done";
            }
        }