LoginSignup
12
16

More than 5 years have passed since last update.

SpringBootでValidationMessages.propertiesをUTF8にしたい私の覚書

Last updated at Posted at 2018-02-21

はじめに

  • Spring Boot 1.5.10
  • 日本語のみ扱うアプリを前提
  • 色々てさぐり

SpringBootでバリデーションをするとデフォルトのエラーメッセージは英語です。
image.png

めいのっとびーえんぷてぃ。ぺらぺーら。

日本人向けアプリを作っているので日本語にしたいです。
日本語化自体は、ValidationMessages.properties というファイルを作って、エラーメッセージを定義すれば可能ですがpropertiesファイルはUnicode変換が必要なため、生で見ると読めません。

org.hibernate.validator.constraints.NotEmpty.message = \u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044\u3002

IDE固有のプラグインで対応する方法もありますが、今回はSpringBoot側でUTF8を受け付けるようにする方法を試してみました。

ちなみに、UTF8で書かれたValidationMessages.propertiesだとエディタでは読めますが、画面表示すると日本語部分がこんな感じで文字化けします。
image.png

追記 バージョンによる違いについて

下記、SpringBootのバージョンによる違いについてコメントをいただいたので捕捉します!

Spring Boot 2.1

Spring Boot 2.1では、特に何もせずともUTF-8化できました。
JDKのバージョンは 11 にする必要があります。

Spring Boot 1.5.3

Spring Boot 1.5.3で試したのですが、public Validator getValidator()をoverrideする方法だとエラーになるみたいです。(エラー内容は参考URLで表示されているものと同じ)
代わりにmvcValidatorのBeanを設定すれば動作しました!

教えて頂いたみなさんありがとうございます:bow_tone1:

やったこと

WebMvcConfigurerAdapterのgetValidatorをOverrideしたげる。だけでした。

WebMvcConfig.java

WebMvcConfig.java
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    /* ・・・ 関係ない設定は省略 ・・・ */

    /**
     * ValidationメッセージをUTF-8で設定できるようにする
     */
    @Override
    public Validator getValidator() {
        return validator();
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

    private MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        //プロパティファイルの名前やディレクトリも変更可能
        messageSource.setBasename("classpath:/ValidationMessages");
        //UTF-8に設定
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

}

ValidationMessages.properties

ValidationMessages.properties
org.hibernate.validator.constraints.NotEmpty.message=入力してください。

読める。読めるぞ。

結果

image.png

ひゃっほーい :relaxed:

参考

Spring Framework Documentation

おわり

12
16
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
16