【问题标题】:Spring Hibernate custom bean validation - NullPointerExceptionSpring Hibernate 自定义 bean 验证 - NullPointerException
【发布时间】:2017-10-01 21:06:12
【问题描述】:

我正在尝试使用注释和 ConstraintValidator 接口创建自定义 bean 验证。目的是使模型的名称唯一。 我不知道为什么,但是当我提交表单以添加产品时,会抛出 NullPointerException。

java.lang.NullPointerException
pl.dsdev.validator.UniqueNameValidator.isValid(UniqueNameValidator.java:20)

模型类:

@Entity
public class Product {

@Id
@GeneratedValue
private long id;

@NotNull(message = "Name is required")
@Size.List({@Size(min = 3, message = "must be longer than {min} characters"), @Size(max = 25, message = "must be shorter than {max} characters")})
@UniqueName(message = "This name is used by another product.")
private String name;

注解界面:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueNameValidator.class)
public @interface UniqueName {

String message() default "";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

ConstraintValidator 的实现:

public class UniqueNameValidator implements ConstraintValidator<UniqueName, String> {

@Autowired
private ProductService productService;

public void initialize(UniqueName uniqueName) {

}

public boolean isValid(String name, ConstraintValidatorContext constraintValidatorContext) {
    return productService.findByName(name)==null;
}

public ProductService getProductService() {
    return productService;
}

public void setProductService(ProductService productService) {
    this.productService = productService;
}
}

我的 root-context.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<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"
   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:p="http://www.springframework.org/schema/p"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="pl.dsdev" />
<mvc:annotation-driven />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/springbaza" />
    <property name="username" value="tutorial" />
    <property name="password" value="password" />
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="pl.dsdev.model" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>

        </props>
    </property>
</bean>

<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="validation"/>
</bean>

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

【问题讨论】:

    标签: java spring hibernate spring-mvc


    【解决方案1】:

    看起来你的productService 没有被 spring 注入(这解释了你得到的 NPE)。

    您要么配置错误(或根本没有配置)spring bean validation

    【讨论】:

    • 你能把ProductService的代码贴出来吗?可能不是有效的 Spring bean。
    • 我添加了 Spring bean 配置文件,你能检查一下是否缺少什么吗?
    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多