dabadaba
dabadaba

Reputation: 9522

Spring: method to validate whole object

Let's say I defined my Entity class with some validation annotations:

public class Entity {
    @Column(unique = true)
    @NotNull
    private String login;

    @NotNull
    private String password;

    @Email
    private String email;
}

I know that a new Entity can be validated using the @Valid annotation in the argument, and the associated error object.

However, I need to create a new Entity in the middle of a different method and I need to validate that the constructed entity is correct (it matches the restrictions declared with annotations in the definition of the class):

public whateverMethod(...) {
    Entity e = new Entity(a, b, c, ...);
    validate(e); // I need something like this
}

I can't find anything like this in the Spring documentation.

Any help?

Upvotes: 0

Views: 1478

Answers (1)

Jean-Philippe Bond
Jean-Philippe Bond

Reputation: 10649

You can inject a Validator object by using the LocalValidatorFactoryBean and then use that validator to validate your entity.

Bean declaration :

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

Your service :

@Service
public class fooService {

    @Autowired
    Validator validator

    public whateverMethod(...) {
        Entity e = new Entity(a, b, c, ...);
        Set<ConstraintViolation<Entity>> = validator.validate(e); 
    }
}

If you don't want to inject the bean, you can do something like this :

public class fooClass {

    public whateverMethod(...) {
        Entity e = new Entity(a, b, c, ...);

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<Entity>> = validator.validate(e); 
    }
}

Note that a JSR-303 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically.

Upvotes: 1

Related Questions