Ответы пользователя по тегу Spring
  • Как заставить работать интернационализацию в ErrorResponse методах?

    devpav
    @devpav
    Full-Stack разработчик.
    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;
        }

    66fb3970b8230342940738.png
    @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, "{", "}");
        }
    }


    66fb3a32a3346675588143.png

    public interface SystemException {
    
        /**
         * Get args for code
         *
         * @return args message
         */
        Map<String, String> getArgs();
    
        /**
         * Exception code
         *
         * @return i18 code
         */
        String getI18Code();
    
    }


    66fb3aa70b97e285459437.png
    Ответ написан
    Комментировать