users@jersey.java.net

[Jersey] Bean Validation Groups

From: Doyle, Brendan <brendan.doyle_at_ie.verizon.com>
Date: Fri, 6 Feb 2015 09:55:51 +0000

Hi

I resolved the issue described below, I thought I would share with this list. I would be interested f anyone has a better solution to this as it is not ideal.
Specifically how to make the ValidatorFactory available to spring for DI.


I was trying to work around the fact that in Jersey the Bean Validation does not support groups.
But I hit a dependency injection problem.

So in my resource class I can inject the ValidatorFactory

@Inject
private ValidatorFactory factory;

and I can do the validation against a particular group.

However I want to extract out the logic here to its own component, call it MyValidator. So I create the MyValidator interface and MyValidatorImpl implementation class and inject the ValidatorFactory into MyValidatorImpl.
I then inject the MyValidator into the resource class

So I have
@Named
public class MyValidatorImpl implements MyValidator {

    @Inject
    private ValidatorFactory factory;



and in the resource class:

@Inject
private MyValidator myValidator;


However spring cannot find ValidatorFactory and when I look it seems that it is Hk2 that was injecting it into the resource class.

So the solution was to let Hk2 manage my new class by creating and registering an AbstractBinder that registers my class with Hk2


public class MyBinder extends AbstractBinder {

    @Override
    protected void configure() {
        bind(MyValidatorImpl.class).to(MyValidator.class);
    }

}




public class Application extends ResourceConfig {
    public Application() {

        register(new MyBinder());
    }
}


Thanks

Brendan Doyle







Verizon Ireland Limited - registered in Ireland - registered number 224334 - registered office at Erne Street, Dublin 2, Ireland - VAT number 8224334A