SpringBoot消息国际化配置实现过程解析

所属分类: 软件编程 / java 阅读数: 49
收藏 0 赞 0 分享

一、目的

针对不同地区,设置不同的语言信息。

SpringBoot国际化配置文件默认放在classpath:message.properties,如果自定义消息配置文件,需要application.properties或application.yml中设置spring.messages.basename的值。

二、步骤

在src/main/resources 下建i18n文件夹

在i18n文件夹中建立messages.properties 找不到语言配置时,使用此文件

hello=你好_默认

在i18n文件夹中建立messages_en_US.properties 英文语言配置

hello=hello_English

在i18n文件夹中建立messages_zh_CN.properties 中文语言配置

hello=你好_中文

MessageConfig.java

对消息的配置

package com.spring.security.config.spring;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.util.Assert;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AbstractLocaleContextResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Configuration
public class MessageConfig extends AbstractLocaleContextResolver{

	@Value("${spring.messages.basename}")
	public String[] basenames;

	@Bean(name = "messageSource")
	public ResourceBundleMessageSource resourceBundleMessageSource() {
		ResourceBundleMessageSource source = new ResourceBundleMessageSource();
		if (basenames != null) {
			for (int i = 0; i < basenames.length; i++) {
				String basename = basenames[i];
				Assert.hasText(basename, "Basename must not be empty");
				this.basenames[i] = basename.trim();
			}
			source.setBasenames(basenames);
		} else {
			this.basenames = new String[0];
			source.setBasename(basenames[0]);
		}
		source.setDefaultEncoding("UTF-8");
		source.setUseCodeAsDefaultMessage(true);
		return source;
	}

  @Bean
  public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
    return slr;
  }

  /**
   * 国际化,设置url识别参数
   *
   * @return
   */
  @Bean
  public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
  }

	@Override
	public LocaleContext resolveLocaleContext(HttpServletRequest request) {
		return null;
	}

	@Override
	public void setLocaleContext(HttpServletRequest request, HttpServletResponse response,
			LocaleContext localeContext) {
	}
}

SpringUtils.java

Spring工具类,用于获取ApplicationContext

package com.spring.security.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * Spring容器
 */
@Service
public class SpringUtils implements ApplicationContextAware {

  private static ApplicationContext context = null;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if (context == null) {
      context = applicationContext;
    }
  }

  /**
   * 获取容器
   *
   * @return 容器
   */
  public static ApplicationContext getContext() {
    return context;
  }
}

MessageUtils.java

封装获取message的工具类

package com.spring.security.common.utils;

import java.util.Locale;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

public class MessageUtils {

	public static String getMessage(String code) {
		 Locale locale = LocaleContextHolder.getLocale();
		 ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
	   String message = reloadableResourceBundleMessageSource.getMessage(code, null, locale);
	   return message;
	}
}

** WebMvcConfig.java**

mvc配置,解决跨域,接口中文乱码,添加语言拦截器

package com.spring.security.config.spring;

import java.nio.charset.Charset;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

	@Autowired
	private LocaleChangeInterceptor localeChangeInterceptor;

	/**
	 * 解决跨域
	 */
	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		registry
		.addMapping("/**")
		.allowedHeaders("*")
		.allowedMethods("*")
		.allowedOrigins("*")
		.allowCredentials(true);
	}

	/**
	 * 配置消息转换器
	 * 解决返回String乱码
	 */
	@Override
	protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		converters.add(responseBodyConverter());
	}

	@Bean
  public HttpMessageConverter<String> responseBodyConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
  }

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

}

三、测试

测试接口:

package com.spring.security.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.spring.security.common.utils.I18nUtils;

@RestController
public class TestController {

	@GetMapping("/test")
	public String doTest() {
		return I18nUtils.getMessage("hello");
	}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java输入输出流复制文件所用时间对比

这篇文章主要介绍了Java输入输出流复制文件所用时间对比的相关资料,非常不错,具有参考解决价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Java线程中start和run方法全面解析

这篇文章主要介绍了Java线程中start和run方法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Java的JSON处理器fastjson使用方法详解

下面小编就为大家带来一篇Java的JSON处理器fastjson使用方法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Java 二维码,QR码,J4L-QRCode 的资料整理

本文主要介绍Java 中二维码,QR码,J4L-QRCode,这里整理了详细的资料供大家学习参考关于二维码的知识,有需要的小伙伴可以参考下
收藏 0 赞 0 分享

java哈夫曼树实例代码

这篇文章主要为大家介绍了java哈夫曼树实例代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android读取本地或网络图片并转换为Bitmap

这篇文章主要为大家详细介绍了Android读取本地或网络图片,并转换为Bitmap,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Java日期时间操作的方法

这篇文章主要为大家详细介绍了Java日期时间操作的一些方法,获得Calendar,定义日期/时间的格式等,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java 获取路径的各种方法(总结)

下面小编就为大家带来一篇java 获取路径的各种方法(总结)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java数据结构与算法之奇偶排序算法完整示例

这篇文章主要介绍了java数据结构与算法之奇偶排序算法,较为详细的分析了奇偶算法的原理并结合完整示例形式给出了实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

java数据结构与算法之双向循环队列的数组实现方法

这篇文章主要介绍了java数据结构与算法之双向循环队列的数组实现方法,结合实例形式分析了双向循环队列的原理与数组实现技巧,并附带说明了该算法的用途,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多