相关疑难解决方法(0)

自定义弹簧验证错误

我想自定义弹簧验证错误

    @NotNull
    @Length(max = 80)
    private String email; 
Run Code Online (Sandbox Code Playgroud)

但我无法做到.要遵循的步骤是什么?

validation customization spring bean-validation

29
推荐指数
1
解决办法
4万
查看次数

Spring Boot 将验证代码映射到 MessageSource 消息

问题:

我正在尝试使用尽可能多的 Spring Boot Auto-configuration 来减少样板代码。我无法让 Spring 验证代码自动映射到我的外部化 messages.properties。只有当我添加自己的LocalValidatorFactoryBean并使用完全限定的 javax 约束消息时,它才会起作用。

目标

我想重写defaultMessage@ javax.validation.constraints.NotNull全球在我的应用程序基于Spring输入验证码秒。

我做的第一件事就是注册这个 bean...我真的必须注册吗?我看到 Spring Boot 有一个,但它似乎与 messages.properties 无关。

@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
  LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
  bean.setValidationMessageSource(messageSource);
  return bean;
}
Run Code Online (Sandbox Code Playgroud)

下一个让我很惊讶。Spring Validation 有这个漂亮的DefaultMessageCodesResolver,它为看起来像这样的失败提供了出色的代码策略:

"code": "NotNull",
"codes": [
   "NotNull.user.firstName",
   "NotNull.firstName",
   "NotNull.java.lang.String",
   "NotNull"
],
Run Code Online (Sandbox Code Playgroud)

但是这些代码甚至不考虑用于@NotNull 约束。验证转换的 spring 文档暗示这样的东西确实存在,但还没有任何有用的东西。

我在这里编写了一个示例应用程序,您可以看到它不起作用。

如何根据messages.properties 中的代码覆盖Spring Validation 错误的默认消息?

相关的build.gradle

  • springBootVersion = '2.0.0.RELEASE'
  • 编译('org.springframework.boot:spring-boot-starter-web')

src/main/resources/messages.properties:

NotNull.user.firstName=This doesn't work
NotNull.firstName=Or …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-boot spring-web

5
推荐指数
1
解决办法
4646
查看次数