Search code examples
jakarta-eeejbbean-validation

Are EJB method parameters validated automatically in a Java EE container?


I'm new to Java Bean Validation so I'm trying to understand how it works.
From what I know, in a Java EE container, with JPA the persistence provider takes care of the validation of the entities so that there's no need to do it programmatically with a Validator.
Are also EJB method parameters validated automatically?

If I have a @Local interface, implemented by an EJB:

@Local
public interface ExampleLocal
{
    void doSomething(@NotNull String param);
}

And I pass null to the above method:

public class Foo 
{
    @EJB
    private ExampleLocal example;

    public void callDoSomething()
    {
        example.doSomething(null);
    }
}

Does the EJB throw an EJBException?


Solution

  • It appears that EJB method parameters are not validated automatically.
    I tested in TomEE and I had to use an Interceptor to validate them

    @Interceptor
    @Validable
    public class ValidationInterceptor
    {
        @Resource
        private Validator validator;
        
        @AroundInvoke
        private Object validate(InvocationContext ic) throws Exception
        {
            ExecutableValidator exVal = validator.forExecutables();
            Set<ConstraintViolation<Object>> violations =  exVal.validateParameters(ic.getTarget(),ic.getMethod(),ic.getParameters());
            if (!violations.isEmpty())
                throw new ConstraintViolationException(violations);
            return ic.proceed();
        }
    }