MessageSource class abstract interface

Turns a message code and a locale into a text in that language, with the arguments filled in.

Use it for every text a user reads that must be translated: labels, e-mails, error messages. The texts live in files such as messages.properties and messages_de.properties (greeting=Hello, {0}!), and code refers to them by code (greeting). Inject MessageSource into a bean, or call getMessage on the context, which is a message source too.

With Spring Boot, putting messages*.properties into lib/resources/ is enough (spring.messages.basename names other files). Without it, declare a bean named messageSource, usually a ReloadableResourceBundleMessageSource. Locales are strings such as ru_RU, ru-RU or ru (see Locales).

// Without Spring Boot: the messages come from i18n/messages*.properties.
@Configuration()
class I18nConfig {
  @Bean()
  MessageSource messageSource() =>
      ReloadableResourceBundleMessageSource(
        basenames: ['file:i18n/messages'],
      );
}

final context = ApplicationContext.run([appBeans]);
context.getMessage('greeting', args: ['Ada'], locale: 'de');

Spring (Java):

@Bean
MessageSource messageSource() {
  var source = new ResourceBundleMessageSource();
  source.setBasenames("i18n/messages");
  return source;
}

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

Unlike Spring, locale is optional: without it only the default locale and the base file are consulted.

Properties

hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

getMessage(String code, {List<Object?> args = const [], String? defaultMessage, String? locale}) → String
The text for code in locale, with args filled into its {0}, {1}, ... placeholders.
getMessageFromResolvable(MessageSourceResolvable resolvable, {String? locale}) → String
The text for the first code of resolvable found in locale, with its arguments filled in; else its default message; else a NoSuchMessageException. Use it to show validation errors and other messages described by codes.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited