public static final String I18_BUNDLE_LOCATION = "language/messages";
@Bean
public ResourceBundleMessageSource resourceBundleMessageSource() {
final var source = new ResourceBundleMessageSource();
{
source.setBasename(I18_BUNDLE_LOCATION);
source.setDefaultEncoding(StandardCharsets.UTF_8.name());
}
return source;
}
@Slf4j
@Service
@RequiredArgsConstructor
public class LocaleI18Service implements LocaleService {
private final ResourceBundleMessageSource messageSource;
@Override
public String getI18Message(final String i18Code) {
return getMessage(i18Code, Map.of());
}
public String getI18Message(final String i18Code, final Map<String, String> args) {
return getMessage(i18Code, args);
}
private String getMessage(final String i18Code, final Map<String, String> args) {
if (Objects.isNull(i18Code)) {
return null;
}
final var currentLocale = LocaleContextHolder.getLocale();
final String template = messageSource.getMessage(i18Code, null, currentLocale);
if (Objects.isNull(args) || args.isEmpty()) {
return template;
}
return StringSubstitutor.replace(template, args, "{", "}");
}
}
public interface SystemException {
/**
* Get args for code
*
* @return args message
*/
Map<String, String> getArgs();
/**
* Exception code
*
* @return i18 code
*/
String getI18Code();
}