没有弹簧如何在javax验证ConstraintValidator中注入bean

时间:2018-09-24 15:29:27

标签: java validation

我使用javax验证。而且我不使用springframework。 我写了特定的注释和特定的ConstraintValidator

public class MyConstraintValidator implements ConstraintValidator<Myconstraints, String> {
  @Override
  public void initialize(...){
  ...
  }

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    System.out.println("value=" + value + ", context=" + context);
    return false;
  }
}

,我需要使用一些外部“服务”来检查“ isValid”方法中的值。 我可以不用springframework DI吗?

我想得到这样的东西:

  ...
  MyService service;       

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
     System.out.println("value=" + value + ", context=" + context);
     if (service.check(value)) {
       return true;
     } else {
       return false; 
     }
  }

1 个答案:

答案 0 :(得分:0)

我的解决方案(感谢帖子https://marcin-chwedczuk.github.io/hello-hibernate-validator的想法):

class MyService {
    public String getProp(){
        return "something";
    }
}

class MyConstraintValidatorFactory implements ConstraintValidatorFactory {

    private MyService service;

    public MyConstraintValidatorFactory(MyService service) {
        this.service = service;
    }

    @Override
    public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
        if (MyConstraintValidator.class.equals(key)) {
            MyConstraintValidator validator = new MyConstraintValidator(this.service);
            return (T) validator;
        }

        if (key.getPackage().getName().startsWith("javax.validation") ||
                key.getPackage().getName().startsWith("org.hibernate.validator"))
        {
            try {
                return key.newInstance();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }

        return null;
    }

    @Override
    public void releaseInstance(ConstraintValidator<?, ?> instance) {
    }
}