メッセージ

メッセージは、ユーザーが読むテキストを言語ごとに一つのファイルにまとめ、コードで引けるようにしたものです。

使う理由

ラベル、メール、エラーメッセージをコードに直接書くべきではありません。直接書くと、アプリケーションの翻訳のたびにすべてのクラスを書き換えることになります。メッセージソースを使うと、テキストは messages.properties、messages_de.properties、messages_ja.properties などに置かれます。コードは greeting のようなコードと de のようなロケールを指定し、引数が埋め込まれたテキストを受け取ります。

言語が一つで、固定のテキストが少しだけのアプリケーションには不要です。

例

# lib/resources/messages.properties
greeting=Welcome to {0}!
# lib/resources/messages_de.properties
greeting=Willkommen bei {0}!
import 'package:spring_core_dart/spring_core_dart.dart';

@Configuration()
class MessagesConfig {
  // Bean 名は `messageSource` でなければならない。コンテキストはこれに委譲する。
  @Bean()
  MessageSource messageSource() =>
      ReloadableResourceBundleMessageSource(basenames: ['resources:messages']);
}

const log = SpringLog('neon');

void main() {
  final context = ApplicationContext.run([appBeans]);
  // コンテキスト自身もメッセージソースである。
  log.info(context.getMessage('greeting', args: ['NEON'], locale: 'de'));
  // Willkommen bei NEON!
  context.close();
}

Spring Boot (spring_boot_dart) を使う場合は、lib/resources/ に messages*.properties を置くだけで十分です。Boot が Bean を宣言します。

ページ一覧

Spring (Java) との対応

@Bean
MessageSource messageSource() {
  var source = new ReloadableResourceBundleMessageSource();
  source.setBasenames("classpath:messages");
  return source;
}

context.getMessage("greeting", new Object[] {"NEON"}, Locale.GERMAN);

ここではロケールは java.util.Locale オブジェクトではなく文字列 (de、ru_RU) で、ロケールの引数は省略できます。

関連項目