SpringBoot3国际化

一、添加国际化资源文件

        

idea中可以下载Resource Bundle Editor插件,同时编辑三个文件信息。

二、配置messageResource设置国际化资源文件

        a.在SpringBoot中提供了MessageSourceAutoConfiguration,所以,我们不需要配置messageResource

        b.但是他并没有生效,开启debug = true

        如果要让它生效必须保存在类路径下的messages文件夹上有国际化的资源文件

        或者自己配置spring.message.basename告诉他资源文件在那。

        application.yml配置如下

spring:
  messages:
    basename: i18n.messages

  

三、需要去解析请求头中的accept-language或者解析url参数中的?local=

其实WebMvcAutoConfiguration类也帮我配置了一个解析请求头上的accept-language的localResolver.

四、要将本地语言进行缓存

需要在自己的配置文件MyWebMvcConfigurer增加监听LocaleChangeInterceptor

和实现LocaleResolver方法。

package com.chj.springbootweb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加国际化拦截器
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        registry.addInterceptor(lci)
                .addPathPatterns("/**");
    }

    @Bean
        public LocaleResolver LocaleResolver() {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        //可以设置过期时间
        localeResolver.setCookieMaxAge(60*6*24*30);
        localeResolver.setCookieName("locale");

        return localeResolver;
    }
}

http://localhost:8085/test-swagger/user/1?locale=en_US

即会读取locale参数的值做为本地语言。并将此参数放到cookie中。

五、通过messageResource获取国际化信息

注入messageSource,调用方法messageSource.getMessage();如下:

    @Autowired
    MessageSource messageSource;

    //Rest /user/1
    @GetMapping("/{id}")
    @Operation(summary = "根据id查询用户的接口")
    @Parameters({@Parameter(name = "id",description = "用户id")})
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功")
    })
    public Result getUser(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        String message =  messageSource.getMessage("user.query.success",null, LocaleContextHolder.getLocale());
        return new Result<User>(200, message,user);
    }

验证:当中文出现乱码时,修改IDEA中资源文件的编码为utf-8

如下图所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值