在 JSF 中使用 Spring 的 LocalValidatorFactoryBean

sie*_*z0r 5 jsf spring dependency-injection autowired bean-validation

我正在尝试将 bean 注入自定义ConstraintValidator. 我遇到了一些事情:

  • 验证 API-1.1.0 支持 CDI(测试版可用)
  • Hibernate Validator 5 似乎实现了validation-api-1.1.0(Alpha可用)
  • 使用 Seam 验证模块
  • 使用 Spring 的 LocalValidatorFactoryBean

最后一个似乎最适合我的情况,因为我们已经在使用 Spring (3.1.3.Release)。

我已将验证器工厂添加到 XML 应用程序上下文并启用了注释:

<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>
Run Code Online (Sandbox Code Playgroud)

验证器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

验证应用于Person

public class Person
{
    @Username
    private String username;
}
Run Code Online (Sandbox Code Playgroud)

和支持 bean:

@Named
@Scope("request")
public class PersonBean
{
    private Person person = new Person();
    @Inject
    private PersonManager personManager;

    public create()
    {
        personManager.create(person);
    }
}
Run Code Online (Sandbox Code Playgroud)

在 JSF 页面中,我有:

<p:inputText value="#{personBean.person.username}" />
Run Code Online (Sandbox Code Playgroud)

验证器被调用,但该字段未自动装配/注入并保持为空。这当然会引发 NullPointerException。

我正在用 Hibernate 验证器 4.2 测试这个(因为LocalValidatorFactoryBean我认为应该能够做到这一点)。

Har*_*rdy 0

我不是 spring 专家,但我希望您也可以在 beans.xml 中定义 PersonManager 或者使用 @Component 对其进行注释。另请参见自动装配带有 @Component 注释的非托管 Bean