1
2

More than 1 year has passed since last update.

【Java/SpringBoot】messages.propertiesを参照して値を出力する

Last updated at Posted at 2022-06-05

SpringBootの機能であるMessageSourceを利用してプロパティ値を参照する方法を記述します。

【view】

【view】.png

【messages.propertiesの作成】

【階層】.png
「resource」直下に「message.properties」を作成します。

【property】コード.png
プロパティ値を作成して表示したい文字列(値)を記述します。
2行目では「{0}世界」とありますが、{0}部分は任意に設定する事ができます。
設定の仕方は【Controller】で説明しています。
※プロパティ値=abc,def部分
※viewでの表示部分HellowWorld,{0}世界

【Controller】

【Java_Controller】.png

■16行目
Autowired機能を使用して「MessageSource」をインポートします。

■21,22行目
message.sourceを使用して値を代入します。
特に22行目では【messages.propertiesの作成】の「{0}世界」の値を任意で設定しています。
※new String[]{"こんにちは"}が該当部分です。

【追記】
propertyから文字エンコードの設定をUTF-8にしておきましょう。
文字化けにより「No message found under code for locale ja_jp」のエラーメッセージが
出ます。

1
2
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
1
2