Spring Boot中的国际化问题在配置文件中不起作用

问题描述

我目前正在使用Spring Boot(包括Spring Security)开发Web应用程序。目前,我正尝试将对默认语言俄语的国际化支持作为开始。 这是一个配置文件,如果用户输入了错误的数据或其他信息,但我返回了英语

,我便在其中写入以俄语获取消息
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

@Configuration

public class ConfigForAuth {
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(new Locale("ru"));
        return slr;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource rs = new ReloadableResourceBundleMessageSource();
        rs.addBasenames("classpath:i18n/messages");
        rs.addBasenames("classpath:/org/springframework/security/messages_ru.properties:1");
        rs.setDefaultEncoding("UTF-8");
        rs.setUseCodeAsDefaultMessage(true);
        return rs;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("locale");

        return localeChangeInterceptor;
    }
}

但是,如果我将在应用程序文件中写入相同的代码,则此代码可以正常工作并在RU中返回给我 申请文件:

@SpringBootApplication
@ComponentScan("--.--.--")//conf
@EnableCaching
@PropertySources({
        @PropertySource("classpath:application.properties"),@PropertySource("classpath:clients.properties")
})
public class OneBpmAuthApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(OneBpmAuthApiApplication.class,args);
    }

解决方法

尝试从WebMvcConfigurerAdapter扩展并添加拦截器。


@Configuration
public class ConfigForAuth extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}
,

我认为以前的建议或多或少是正确的,只是需要将ParamName设置为“ lang”,如下所示:

   @Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeChangeInterceptor = new
            LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    return localeChangeInterceptor;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

还请记住要扩展WebMvcConfigurer。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...