全局设置自定义 Spring 验证消息

问题描述 投票:0回答:1

有没有办法在全局范围内为特定约束/验证器设置错误消息? IE。我希望所有

@NotNull
约束都有验证消息(如
"Need a value here"
或其他),而不是在每次出现时都写
@NotNull(message=...)

是否可以全局定义默认消息?

我尝试将类似以下内容的内容放入 messages.properties 文件中。但没有成功。

javax.validation.constraints.NotNull.message=...
spring spring-boot
1个回答
0
投票

我相信您需要覆盖默认的验证器才能使用您的自定义消息,可以像这样完成

@Configuration
public class WebConfig implements WebMvcConfigurer
{
    private final MessageSource messageSource;

    public WebConfig(MessageSource messageSource)
    {
        this.messageSource = messageSource;
    }

    @Bean
    @Override
    public LocalValidatorFactoryBean getValidator() 
    {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource);
        return bean;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.