LoginSignup
16
16

More than 5 years have passed since last update.

メッセージの外出し(Spring boot)

Posted at

手順1~applicaton.propertiesの設定~

src/main/resources/application.propertiesに以下の様に書きます。
日本語環境でロケールがjaの場合、messages_ja.propertiesを読み込む。

application.properties
spring.messages.basename=messages  //ファイル名(拡張子不要)
spring.messages.cache-duration=-1
spring.messages.encoding=UTF-8 

手順2~messages.propertiesの設定(メッセージ用ファイル)~

src/main/resources/messages.propertiesを作成

messages.propertiesというファイルがないと messageSource の auto-configuration が実行されないため、起動時にエラーメッセージ出るので、空ファイルを作成しておくこと。

多言語化

多言語化する時には、messagesの後ろにロケールを示す文字、例えば英語(en)なら、messages_en.properties,日本語ならmessages_ja.propertiesのようにファイルを用意することになります。
今回は日本語を意味するロケールmessages_ja.propertiesを作成。

messages_ja.properties

# ハローワールド
hello.world=ハローワールド

手順3~Java側での参照~

MessageSource をプロパティとして定義する。

UserController.java

@Controller
public class UserController {

@Autowired
protected MessageSource messageSource;

@RequestMapping("/")
public String hello(Model model) {

     model.addAttribute("Msg", messageSource.getMessage("hello.world", null, Locale.JAPAN));
     return "hello";
   }

}

手順4~HTML + thymeleafでの参照~

hello.html

<h1 th:text="${Msg}">XXXXX</h1>

その他~HTML+tymeleafで直接参照する~

hello.html

<h1 th:text="#{hello.world}">XXXXX</h1>

16
16
0

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
16
16