広告 Spring Boot

Spring Bootで多言語対応する方法

Spring Bootで多言語対応の手順

Spring Bootにはデフォルトで多言語の機能(i18n)がついています。その機能を利用すれば多言語化対応は簡単にできます。本記事ではSpring Bootの多言語対応の手順について紹介します。

スポンサーリンク

[手順1] 多言語ファイルの作成

今回は日本語と英語の多言語ファイルを作成します。

src.main.resources配下に、日本語と英語用のプロパティファイルを作成します。

※Springのデフォルトの配置場所がsrc.main.resources配下です。

[messages_ja.properties]

hello=こんにちは世界!!

[messages_en.properties]

hello=Hello World!!

_jaや_enが言語を表す部分です。

[手順2] 多言語ファイルの読み込み

次に多言語ファイルを読み込みます。

package com.example.demo.controller;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* HelloWorld Controller
*/
@Controller
public class HelloWorldController {

/**
* メッセージ管理
*/
@Autowired
private MessageSource messageSource;

/**
* HelloWorld表示
* @param model Model
* @return HelloWorld表示画面
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String helloWorld(Model model) {
String[] param = new String[] {};
model.addAttribute("message",messageSource.getMessage("hello", param, Locale.JAPAN));
return "index";
}
}

messageSource.getMessage("hello", param, Locale.JAPAN) を使用して多言語ファイルを読み込みます。

  • 第一引数:キー値
  • 第二引数:動的パラメータ
  • 第三引数:言語

第三引数の言語により、読み込むファイルの切り分けを行います。読み込むファイルが存在しない場合は、システムのデフォルト言語のファイルを読み込みます。

これで多言語化は終了です。クライアントからHTTPヘッダに表示する言語を含ませて、サーバ側では、HTTPヘッダに記載されている言語で返却するような流れが、よくある流れです。

多言語ファイルに動的パラメータを設定する方法

言語ファイルに動的パラメータを設定する方法は以下の通り。

言語ファイルに動的パラメータが入る場所の指定をします。指定方法は{数値}の形式で指定します。※数値は0から順番に設定

[messages_ja.properties]

hello=こんにちは世界!!{0}{1}

言語ファイルを読み込む処理では、messageSource.getMessageメソッドの第二引数に動的パラメータを設定します。

String[] param = new String[] {"動的パラメータ1","動的パラメータ2"};
model.addAttribute("message",messageSource.getMessage("hello", param, Locale.JAPAN));

helpful