
# 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

```properties
# lib/resources/messages.properties
greeting=Welcome to {0}!
# lib/resources/messages_de.properties
greeting=Willkommen bei {0}!
```

```dart
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

- [MessageSource](message-source.md): the `MessageSource` interface, `ReloadableResourceBundleMessageSource`, `StaticMessageSource`, `MessageSourceAccessor` and the `MessageFormat` syntax of the texts.

## In Spring (Java)

```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

- [Resources](../resources/index.md)
- [Validation](../validation/index.md)
- [@Bean](../beans/bean.md)
- [ApplicationContext](../beans/application-context.md)
