springboot国际化处理

发布时间 2023-06-26 11:56:31作者: 咸蛋solo粥

在Spring Boot程序中实现国际化主要有以下几个步骤
1.添加MessageSource组件
Spring Boot自动配置了MessageSource,它读取消息资源bundle,并支持国际化。我们只需要在application.properties中指定basename即可:

spring.messages.basename=messages

这会查找messages.properties和messages_zh_CN.properties等文件。

  1. 创建消息资源文件
    在src/main/resources目录下创建messages.properties:
hello=Hello
success=Success

创建messages_zh_CN.properties:

hello=你好
success=成功

创建messages_en_US.properties:

hello=Hello
success=Success
  1. 注入MessageSource并使用
    在Controller或Service中注入MessageSource,根据Locale解析消息:
// 注入成员变量
@Autowired
private MessageSource messageSource;

// 在调用方法中执行
// 获取当前的地区,根据地区获取对应的资源
Locale locale = LocaleContextHolder.getLocale();
String hello = messageSource.getMessage("hello", null, locale);

  1. 根据请求头解析Locale
    可以在Interceptor中获取请求头的语言参数,并解析成Locale注入到RequestContext,这样MessageSource就会自动使用该Locale:
@Component
public class LocaleInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, 
                             HttpServletResponse response, 
                             Object handler) throws Exception {
        // 根据请求头判断语言
        String language = request.getHeader("language");
        Locale locale = language == null ? Locale.getDefault() : Locale.forLanguageTag(language);

        // 线程安全的,底层是用ThreadLocal来存储的。
        // 设置地区。
        LocaleContextHolder.setLocale(locale);
        return true;
    }
}
  1. 注册拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LocaleInterceptor localeInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeInterceptor )
                .addPathPatterns("/**"); // 设置拦截路径
//                .excludePathPatterns("/login"); // 设置排除路径
    }
}