0


Spring boot实现国际化

Spring boot国际化支持

当我们web项目涉及到国外部署或者国外用户使用时,需要展示不同语言信息,所以就需要国际化支持,下面将讲解Springboot国际化支持操作

1. 修改Springboot

application.yml

配置

spring:messages:basename: i18n/messages #配置国际化资源文件路径

2. 创建国际化资源文件

在这里插入图片描述

messages.properties

不带后缀为默认语言资源

  • 简体中文 messages_zh_CN.properties``````unknown.exception=未知异常,请联系管理员!user.login.notExists={0} 用户不存在!
  • 英文 messages_en_US.properties``````unknown.exception=Unknown error,Please contact the administrator!user.login.notExists={0} user not exists!
  • messages.properties文件内容就和简体中文文件一致,如果未设置Locale参数,默认就为该文件内容,此文件也可不用unknown.exception=未知异常,请联系管理员!user.login.notExists={0} 用户不存在!

3. 创建SpringUtil类

创建SpringUtil工具类,方便其他工具类(未被Spring管理的class)获取Spring容器中的实例。

importcom.central.common.utils.StringUtils;importorg.springframework.aop.framework.AopContext;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.NoSuchBeanDefinitionException;importorg.springframework.beans.factory.config.BeanFactoryPostProcessor;importorg.springframework.beans.factory.config.ConfigurableListableBeanFactory;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ApplicationContextAware;importorg.springframework.stereotype.Component;/**
 * spring工具类 方便在非spring管理环境中获取bean
 *
 * @author xq0136
 */@ComponentpublicfinalclassSpringUtilsimplementsBeanFactoryPostProcessor,ApplicationContextAware{/** Spring应用上下文环境 */privatestaticConfigurableListableBeanFactory beanFactory;privatestaticApplicationContext applicationContext;@OverridepublicvoidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)throwsBeansException{SpringUtils.beanFactory = beanFactory;}@OverridepublicvoidsetApplicationContext(ApplicationContext applicationContext)throwsBeansException{SpringUtils.applicationContext = applicationContext;}/**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     *
     */@SuppressWarnings("unchecked")publicstatic<T>TgetBean(String name)throwsBeansException{return(T) beanFactory.getBean(name);}/**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws BeansException
     *
     */publicstatic<T>TgetBean(Class<T> clz)throwsBeansException{T result =(T) beanFactory.getBean(clz);return result;}/**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     *
     * @param name
     * @return boolean
     */publicstaticbooleancontainsBean(String name){return beanFactory.containsBean(name);}/**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     *
     */publicstaticbooleanisSingleton(String name)throwsNoSuchBeanDefinitionException{return beanFactory.isSingleton(name);}/**
     * @param name
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException
     *
     */publicstaticClass<?>getType(String name)throwsNoSuchBeanDefinitionException{return beanFactory.getType(name);}/**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     *
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     *
     */publicstaticString[]getAliases(String name)throwsNoSuchBeanDefinitionException{return beanFactory.getAliases(name);}/**
     * 获取aop代理对象
     *
     * @param invoker
     * @return
     */@SuppressWarnings("unchecked")publicstatic<T>TgetAopProxy(T invoker){return(T)AopContext.currentProxy();}/**
     * 获取当前的环境配置,无配置返回null
     *
     * @return 当前的环境配置
     */publicstaticString[]getActiveProfiles(){return applicationContext.getEnvironment().getActiveProfiles();}/**
     * 获取当前的环境配置,当有多个环境配置时,只获取第一个
     *
     * @return 当前的环境配置
     */publicstaticStringgetActiveProfile(){finalString[] activeProfiles =getActiveProfiles();returnStringUtils.isNotEmpty(activeProfiles)? activeProfiles[0]:null;}}

4. 创建MessageUtils工具类,获取message

Spring提供了 MessageSource来实现国际化操作,原理后续编写 todo

importcom.xq.util.spring.SpringUtils;importorg.springframework.context.MessageSource;importorg.springframework.context.i18n.LocaleContextHolder;/**
 * 获取i18n资源文件
 *
 */publicclassMessageUtils{/**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */publicstaticStringmessage(String code,Object... args){MessageSource messageSource =SpringUtils.getBean(MessageSource.class);return messageSource.getMessage(code, args,LocaleContextHolder.getLocale());}}

5. java代码中使用

MessageUtils

实现国际化操作

@GetMapping("test")publicStringgetRedisTest(){String msg1 =MessageUtils.message("unknown.exception");String msg2 =MessageUtils.message("user.login.notExists","123456");return msg1+"\n"+msg2;}

请求测试接口返回结果:
在这里插入图片描述

6. 添加国际化拦截器

@ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{/**
     * 国际化配置
     */@BeanpublicLocaleResolverlocaleResolver(){//        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();//        sessionLocaleResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);//        return sessionLocaleResolver;//使用CookieLocaleResolver,也可使用SessionLocaleResolver,区别在于一个使用Cookie存储Locale信息,一个使用SessionCookieLocaleResolver localeResolver =newCookieLocaleResolver();
        localeResolver.setCookieName("localeCookie");//设置默认区域
        localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        localeResolver.setCookieMaxAge(3600);//设置cookie有效期.return localeResolver;}/**
     *
     * 添加Locale 拦截器,从请求参数lang中获取参数值,这样我们可以通过lang RequestParam来切换Locale信息
     */@BeanpublicLocaleChangeInterceptorlocaleChangeInterceptor(){LocaleChangeInterceptor localeChangeInterceptor =newLocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");return localeChangeInterceptor;}@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){//添加locale拦截器
        registry.addInterceptor(localeChangeInterceptor());}}

如图:

在这里插入图片描述

标签: spring java spring boot

本文转载自: https://blog.csdn.net/qq_42315935/article/details/125337214
版权归原作者 如风如云如雨如你 所有, 如有侵权,请联系我们删除。

“Spring boot实现国际化”的评论:

还没有评论