Messages

Messages are the texts users read, kept in one file per language and looked up by code.

Why use it

Labels, mails and error messages should not be written in the code. When they are, translating the application means editing every class. With a message source, the texts live in messages.properties, messages_de.properties, messages_ja.properties and so on. Code asks for a code, such as greeting, in a locale, such as de, and gets the text with its arguments filled in.

You do not need it for an application with one language and a few fixed texts.

Example

# 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 {
  // The bean must be named `messageSource`; the context delegates to it.
  @Bean()
  MessageSource messageSource() =>
      ReloadableResourceBundleMessageSource(basenames: ['resources:messages']);
}

const log = SpringLog('neon');

void main() {
  final context = ApplicationContext.run([appBeans]);
  // The context is a message source too.
  log.info(context.getMessage('greeting', args: ['NEON'], locale: 'de'));
  // Willkommen bei NEON!
  context.close();
}

With Spring Boot (spring_boot_dart), messages*.properties in lib/resources/ is enough; Boot declares the bean.

Pages

In Spring (Java)

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

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

Locales are strings here (de, ru_RU), not java.util.Locale objects, and the locale argument is optional.

See also