当前位置: 首页 > 知识库问答 >
问题:

Spring Hibernate自定义bean验证-NullPointerException

楚墨一
2023-03-14

我试图使用注释和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 {};
}
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"/>

共有1个答案

汪和悌
2023-03-14

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

您要么错误配置(要么根本没有配置)spring bean验证。

 类似资料:
  • 表单验证发生在数据验证之后。如果你需要定制化这个过程,有几个不同的地方可以修改,每个地方的目的不一样。表单处理过程中要运行三种类别的验证方法。它们通常在你调用表单的is_valid() 方法时执行。还有其它方法可以触发验证过程(访问errors 属性或直接调用full_clean() ),但是通用情况下不需要。 一般情况下,如果处理的数据有问题,每个类别的验证方法都会引发ValidationErr

  • 任何进入CustomValidator实现的bean都始终为空。我使用的是Spring Boot 2,应用程序是REST API,我没有使用MVC。 我已经尝试了所有我读到的关于这件事的东西,但到目前为止运气都不好。 例如,这里的这个话题对我来说并不适用 否则我应该验证吗?,我已经坚持了2天了。 这是我的配置类: 我的CustomValidator如下所示: JPA实体: 注释:

  • 我正在尝试编写一个自定义bean验证器,并根据用户界面上的语言环境显示验证消息。 为此,我创建了一个验证器,如下所示: 我还注册了messageSource和validator bean: 在我的控制器中,我使用initBinder注册我的验证器: 不过,验证错误消息在用户界面上显示为{myproject.myclass.validation.name}。即使我设置了LocalValidatorF

  • 我想知道你是否可以使用vee validate插件编写自定义日期验证,其中结束日期不能小于开始日期?我到处寻找,我找不到确切的答案。 如果没有办法实现这一点,那么我可以凑合着没有它,但是,现在我已经在我的模板中实现了我的开始日期是: 我的脚本如下所示: 但是没有出现任何验证。我想我在我的脚本中丢失了一些东西,但我不确定如何将日期实现到那里。任何帮助将不胜感激。

  • 问题内容: 我有一个非常简单的表格: 这是自定义表单验证的完成方式吗?我需要评估该电子邮件地址当前没有用户存在。我还需要评估并匹配。我该怎么做呢? 问题答案: 要单独验证单个字段,可以在表单中使用clean_FIELDNAME()方法,因此对于电子邮件: 然后对于相互依赖的共同依赖字段,你可以覆盖在单独验证所有字段(email如上)之后运行的 方法: 我不确定你从哪里来,但是看起来这是为m你的表单

  • 问题内容: 我想自定义弹簧验证错误 但是我做不到。要采取的步骤是什么? 问题答案: 该JSR 303的默认邮件插补算法,您可以通过提供捆绑命名的资源来定制信息。在类路径中创建一个文件,其中包含: 这将更改@Size约束的默认消息,因此您应该使用@Size约束而不是特定于Hibernate的@Length约束。 您可以更改特定约束实例的消息,而不是更改所有约束的默认消息。message在约束上设置属