I am trying to get a bean injected into a custom ConstraintValidator
. I have come across some things:
- CDI is supported in validation-api-1.1.0 (Beta available)
- Hibernate Validator 5 seems to implement validation-api-1.1.0 (Alpha available)
- Use Seam validation module
- Use Spring's LocalValidatorFactoryBean
The last one seems most appropriate for my situation since we're already using Spring (3.1.3.Release).
I have added the validator factory to the XML application context and annotations are enabled:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.example" />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</beans>
The validator:
public class UsernameUniqueValidator implements
ConstraintValidator<Username, String>
{
@Autowired
private PersonManager personManager;
@Override
public void initialize(Username constraintAnnotation)
{
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
if (value == null) return true;
return personManager.findByUsername(value.trim()) != null;
}
}
The validation is applied to a Person
:
public class Person
{
@Username
private String username;
}
And the backing bean:
@Named
@Scope("request")
public class PersonBean
{
private Person person = new Person();
@Inject
private PersonManager personManager;
public create()
{
personManager.create(person);
}
}
And in the JSF page I have:
<p:inputText value="#{personBean.person.username}" />
The validator is invoked but the field is not autowired/injected and stays null. This of course trows a NullPointerException.
I am testing this with Hibernate validator 4.2 (since LocalValidatorFactoryBean
should be able to do this I think).