SpringBoot internationalization configuration

1. Create a resource file

Name the new directory under resources: i18n, and then define the resource file 'Resource Bundle' under the i18n directory file and
insert image description here
add internationalization files messages.properties, messages_en_US.properties, messages_zh_CN.properties
insert image description here

2. Modify the configuration file

Modify the basename internationalization file in the configuration application.yml, the default is the messages file under the i18n path
(for example, the current internationalization file is xx_zh_CN.properties, xx_en_US.properties, then the basename configuration should be i18n/xx)

spring:
  # 资源信息
  messages:
    # 国际化资源文件路径
    basename: static/i18n/messages

3. Add configuration class

Two ways, one is to get the language from the parameter, the other is to get the language from the Header

Parameter to get the language ID

@Configuration
public class I18nConfig extends WebMvcConfigurerAdapter {
    
    
    @Bean
    public LocaleResolver localeResolver() {
    
    
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return slr;
    }

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

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

}

Get the language ID from the Header

@Configuration
public class I18nConfig implements LocaleResolver {
    
    

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
    
    
        Locale locale = Locale.CHINA;
        String language = request.getHeader("Accept-Language");
        if (StringUtils.isNotBlank(language)) {
    
    
            String[] splitLanguage = language.split("_");
            if (splitLanguage.length > 1) {
    
    
                locale = new Locale(splitLanguage[0], splitLanguage[1]);
            }
        }
        return locale;
    }

    @Override
    public void setLocale(
            HttpServletRequest request,
            HttpServletResponse response,
            Locale locale) {
    
    
        //ignore
    }

    @Bean
    public LocaleResolver localeResolver() {
    
    
        return new I18nConfig();
    }
}

4. Tools

The spring tool class is convenient for obtaining beans in a non-spring management environment

@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
    
    
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {
    
    
        SpringUtils.beanFactory = beanFactory;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws org.springframework.beans.BeansException
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException
    {
    
    
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws org.springframework.beans.BeansException
     *
     */
    public static <T> T getBean(Class<T> clz) throws BeansException
    {
    
    
        T result = (T) beanFactory.getBean(clz);
        return result;
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name)
    {
    
    
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     * @param name
     * @return boolean
     * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
     *
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {
    
    
        return beanFactory.isSingleton(name);
    }

    /**
     * @param name
     * @return Class 注册对象的类型
     * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
     *
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
    {
    
    
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     *
     * @param name
     * @return
     * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
     *
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {
    
    
        return beanFactory.getAliases(name);
    }

    /**
     * 获取aop代理对象
     * 
     * @param invoker
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker)
    {
    
    
        return (T) AopContext.currentProxy();
    }
}

5. Get the i18n resource file

According to the message key and parameters, the message is delegated to spring messageSource

public class MessageUtils
{
    
    
    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args)
    {
    
    
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }
}

6. Use i18n internationalization

Write translation values ​​to Resource Bundle resource files

American English messages_en_US.properties

user.login.username=User name
user.login.password=Password
user.login.code=Security code
user.login.remember=Remember me
user.login.submit=Sign In

Simplified Chinese messages_zh_CN.properties

user.login.username=用户名
user.login.password=密码
user.login.code=验证码
user.login.remember=记住我
user.login.submit=登录

Use MessageUtils for internationalization

MessageUtils.message("user.login.username")
MessageUtils.message("user.login.password")
MessageUtils.message("user.login.code")
MessageUtils.message("user.login.remember")
MessageUtils.message("user.login.submit")

Switch languages ​​synchronously with vue project or uniapp

vue
uniapp

Guess you like

Origin blog.csdn.net/qq_41596778/article/details/129958260