Method validation with Weld and Hibernate Validator

928 views Asked by At

Does anyone know how to get method validation to run when using Weld and Hibernate Validator? My application should be a standalone application, so I'm not using an application server.

The @NotNull constraint for the method test in my code below is simply ignored.

My code is this:

Test.java

package com.example.methodvalidation;

import org.jboss.weld.environment.se.bindings.Parameters;
import org.jboss.weld.environment.se.events.ContainerInitialized;

import javax.enterprise.event.Observes;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import java.util.List;

@Singleton
public class Test {

    public void main(@Observes ContainerInitialized event, @Parameters List<String> parameters) {
        test("Hello method validation");
        test(null);
    }

    public void test(@NotNull String s) {
        System.out.println(s);
    }
}

validation.xml

<?xml version="1.0" encoding="UTF-8"?>
<validation-config
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration"
    version="1.1">
    <executable-validation>
        <default-validated-executable-types>
            <executable-type>ALL</executable-type>
        </default-validated-executable-types>
    </executable-validation>
</validation-config>

I'm using Gradle to build; this is my gradle.build with the dependencies:

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'org.jboss.weld.environment.se.StartMain'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.hibernate:hibernate-validator:5.0.2.Final",
            "org.hibernate:hibernate-validator-cdi:5.0.2.Final",
            "org.jboss.weld.se:weld-se:2.1.1.Final",
            "javax.el:javax.el-api:2.2.4",
            "org.glassfish.web:javax.el:2.2.4"
}

I tried to use the Hibernate Validator CDI which is mentioned in their Getting started guide with "org.hibernate:hibernate-validator-cdi:5.0.2.Final", but this didn't work either.

What am I missing to get method validation to run?

1

There are 1 answers

0
Sun On BEST ANSWER

Solved it by myself: Calling a method in the same class is not treated as a business method invocation and therefore validation doesn't take place. If the invoked method is moved to a separate class which is then injected into the Test class above, it works.

For more, see here: https://community.jboss.org/thread/234467