0

I have a Spring 4 app with hibernate-validator on the classpath. I have a bean class which uses some javax validation annotations for the bean properties and I have another class that accepts that bean in it's constructor.

Java:

public class Config {

    @NotNull
    @Size(min=10)
    public final String test;

    @Min(5) 
    public final int num;

    public Config(String test, int num) {
        this.test = test;
        this.num = num;
    }

    //getters
}

public class Test {
  private Config config;
  public Test(@Valid Config config) {
     this.config = config;
  }
}

My Spring application context is as follows:

<bean id="config" class="com.Config">
    <constructor-arg type="java.lang.String">
        <value>aaaa</value>
    </constructor-arg>
    <constructor-arg type="int">
        <value>2</value>
    </constructor-arg>
</bean>

<bean id="test" class="com.Test">
    <constructor-arg ref="config" />
</bean>

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

Note that the validator is defined in the application context. When I run the app as is, I expect an exception to be thrown when the bean is set into the test class constructor because the two arguments do not meet the constraints, but it runs without any exception. Am I missing something else?

user1491636
  • 2,355
  • 11
  • 44
  • 71

1 Answers1

1

The @Valid annotation is meant to be used for Controller methods, so it's not being evaluated here in your constructor.

This old question indicates how you can test the @Valid annotation by exposing and calling a Controller using Spring MVC. Also, if you notice other annotations are not working, make sure you have <mvc:annotation-driven /> somewhere in your context file.

Community
  • 1
  • 1
Dean Clark
  • 3,770
  • 1
  • 11
  • 26
  • So is there no way to auto-validate? Do I need to explicity call the validate methods using a validator? This is not a webapp. – user1491636 May 18 '16 at 19:26
  • You can implement `InitializingBean` in your class, Autowire in the Validator (`@Autowired Validator validator`), and then call the validator on `validator.validate(this)` and Assert that it returns an empty set. – Dean Clark May 18 '16 at 19:34