@Component
public class Messages
{
@Autowired
private MessageSource messageSource;
private MessageSourceAccessor accessor;
// To let the messages accessed statically
private static Messages ownInstance;
// Default locale for your app.
// app.default.locale expected to be available in application.properties/yml
@Value("${app.default.locale}")
private String defaultLocale;
@PostConstruct
public void init()
{
Locale.setDefault(new Locale(defaultLocale));
accessor = new MessageSourceAccessor(messageSource);
ownInstance = this;
}
private String getString(String key)
{
try
{
return accessor.getMessage(key);
} catch (MissingResourceException e)
{
return '!' + key + '!';
}
}
/**
* Returns the Locale specific message from the configured
* {@link MessageSource}
*
* @param theKey
* The key for which the message will be returned.
* @return The message string associated with the given key.
*/
public static String getMessage(String theKey)
{
return ownInstance.getString(theKey);
}
}