LoginSignup
30
39

More than 5 years have passed since last update.

Spring メッセージ管理(MessageSource)

Last updated at Posted at 2017-02-14

メッセージ定義

メッセージをプロパティファイル(messages.properties)に定義する。
ここでは日本語用のプロパティファイル(messages_ja.properties)を作成。

messages_ja.properties
hoge={0}さん、おはようございます。

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

MessageSourceの利用

MessageSourceをインジェクションしてgetMessageメソッドを呼び出す。

sample.java
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleMessage {

    @Autowired
    MessageSource messagesource;

    @RequestMapping ("/show")
    public void showMessage(){
        String message = messagesource.getMessage("hoge", new String[]{"fuga"}, Locale.JAPAN);
        System.out.println(message);

    }
}

起動後、ブラウザで http://localhost:8080/show にアクセスすると
「fugaさん、おはようございます。」が表示される。

MessageSourceResolvableの利用

メッセージに埋め込む値もプロパティから取得したい場合、MessageSourceResolvableを利用する。

messages_ja.properties
hoge={0}さん、おはようございます。
Name=fuga
sample2.java
@RestController
public class SampleMessage {

    @Autowired
    MessageSource messagesource;

    MessageSourceResolvable Name = new DefaultMessageSourceResolvable("Name");

    @RequestMapping ("/show")
    public void showMessage(){
        String message = messagesource.getMessage("hoge", new MessageSourceResolvable[] {Name}, Locale.JAPAN);
        System.out.println(message);

    }
}

起動後、ブラウザで http://localhost:8080/show にアクセスすると
「fugaさん、おはようございます。」が表示される。

Thymeleaf での利用

Thymeleafのテンプレートからは#{key}で取得することができる。

messages_ja.properties
hello.wolrd=こんにちわ、世界。
sample3.java
@Controller
public class SampleMessage {    
    @RequestMapping ("/sample")
    public String showSample(){
        return "Sample/Sample";
    }
}

sorce/main/resources/templatesにSample/Sample.htmlを作成

Sample.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Sample</title>
    <meta charset="UTF-8"/>
</head>
<body>
    <h1 th:text="#{hello.wolrd}"></h1>
</body>
</html>

起動後、ブラウザで http://localhost:8080/Sample にアクセスすると
こんにちわ、世界。」が表示される。

30
39
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
30
39