SpringBoot源码学习系列之Locale自动配置
@
MessageSourceAutoConfiguration是国际化语言i18n的自动配置类
MessageSourceAutoConfiguration.ResourceBundleCondition 源码:
protected static class ResourceBundleCondition extends SpringBootCondition {
//定义一个map缓存池
private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<>();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
ConditionOutcome outcome = cache.get(basename);//缓存拿得到,直接从缓存池读取
if (outcome == null) {//缓存拿不到,重新读取
outcome = getMatchOutcomeForBasename(context, basename);
cache.put(basename, outcome);
}
return outcome;
}
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle");
for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) {
//匹配resource bundle资源
return ConditionOutcome.match(message.found("bundle").items(resource));
}
}
}
return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
}
//解析资源文件
private Resource[] getResources(ClassLoader classLoader, String name) {
String target = name.replace('.', '/');//spring.messages.basename参数值的点号换成斜杆
try {
return new PathMatchingResourcePatternResolver(classLoader)
.getResources("classpath*:" + target + ".properties");
}
catch (Exception ex) {
return NO_RESOURCES;
}
}
}
ok,这个自动配置类还是比较容易理解的,所以本博客列举一些注意要点
1、spring.messages.cache-duration
- spring.messages.cache-duration在2.2.1版本,指定的是s为单位,找到SpringBoot的MessageSourceAutoConfiguration自动配置类

2、LocaleResolver 的方法名必须为localeResolver
- 如下代码,LocaleResolver 的方法名必须为localeResolver,否则会报错
@Bean
public LocaleResolver localeResolver(){
CustomLocalResolver localResolver = new CustomLocalResolver();
localResolver.setDefaultLocale(webMvcProperties.getLocale());
return localResolver;
}
原理:
跟一下源码,点进LocaleChangeInterceptor类


DispatcherServlet是Spring一个很重要的分发器类,在DispatcherServlet的一个init方法里找到这个LocaleResolver的init方法

这个IOC获取的bean类名固定为localeResolver,写例子的时候,我就因为改了bean类名,导致一直报错,跟了源码才知道Bean类名要固定为localeResolver

3、默认LocaleResolver
继续跟源码,抛异常的时候,也是会获取默认的LocaleResolver的



找到一个properties配置文件,全局搜索

找到资源文件,确认,还是默认为AcceptHeaderLocaleResolver

4、指定默认的locale
- WebMvcAutoConfiguration的自动配置
配置了locale属性的时候,还是选用AcceptHeaderLocaleResolver作为默认的LocaleResolver
spring.mvc.locale=zh_CN
WebMvcAutoConfiguration.localeResolver方法源码,ConditionalOnMissingBean主键的意思是LocaleResolver没有自定义的时候,才作用,ConditionalOnProperty的意思,有配了属性才走这里的逻辑

5、localeChangeInterceptor指定传参
- 拦截器拦截的请求参数默认为locale,要使用其它参数,必须通过拦截器设置 ,eg:
localeChangeInterceptor.setParamName("lang");

附录:
- Locale解析器种类
LocalResolver种类有:CookieLocaleResolver(Cookie)、SessionLocaleResolver(会话)、FixedLocaleResolver、AcceptHeaderLocaleResolver(默认)、.etc
具体实现,参考我的博客:SpringBoot系列之i18n国际化多语言支持教程
SpringBoot源码学习系列之Locale自动配置的更多相关文章
- SpringBoot源码学习系列之异常处理自动配置
SpringBoot源码学习系列之异常处理自动配置 1.源码学习 先给个SpringBoot中的异常例子,假如访问一个错误链接,让其返回404页面 在浏览器访问: 而在其它的客户端软件,比如postm ...
- SpringBoot源码学习系列之SpringMVC自动配置
目录 1.ContentNegotiatingViewResolver 2.静态资源 3.自动注册 Converter, GenericConverter, and Formatter beans. ...
- SpringBoot源码学习系列之嵌入式Servlet容器
目录 1.博客前言简单介绍 2.定制servlet容器 3.变换servlet容器 4.servlet容器启动原理 SpringBoot源码学习系列之嵌入式Servlet容器启动原理 @ 1.博客前言 ...
- SpringBoot源码学习系列之@PropertySource不支持yaml读取原因
然后,为什么@PropertySource注解默认不支持?可以简单跟一下源码 @PropertySource源码: 根据注释,默认使用DefaultPropertySourceFactory类作为资源 ...
- SpringBoot源码学习系列之启动原理简介
本博客通过debug方式简单跟一下Springboot application启动的源码,Springboot的启动源码是比较复杂的,本博客只是简单梳理一下源码,浅析其原理 为了方便跟源码,先找个Ap ...
- 源码学习系列之SpringBoot自动配置(篇一)
源码学习系列之SpringBoot自动配置源码学习(篇一) ok,本博客尝试跟一下Springboot的自动配置源码,做一下笔记记录,自动配置是Springboot的一个很关键的特性,也容易被忽略的属 ...
- 源码学习系列之SpringBoot自动配置(篇二)
源码学习系列之SpringBoot自动配置(篇二)之HttpEncodingAutoConfiguration 源码分析 继上一篇博客源码学习系列之SpringBoot自动配置(篇一)之后,本博客继续 ...
- SpringBoot源码解析系列文章汇总
相信我,你会收藏这篇文章的 本篇文章是这段时间撸出来的SpringBoot源码解析系列文章的汇总,当你使用SpringBoot不仅仅满足于基本使用时.或者出去面试被面试官虐了时.或者说想要深入了解一下 ...
- Java并发包源码学习系列:阻塞队列BlockingQueue及实现原理分析
目录 本篇要点 什么是阻塞队列 阻塞队列提供的方法 阻塞队列的七种实现 TransferQueue和BlockingQueue的区别 1.ArrayBlockingQueue 2.LinkedBloc ...
随机推荐
- 【RabbitMQ】使用学习
[RabbitMQ]使用学习 转载: ============================================================= =================== ...
- python爬虫获取天猫与京东的商品价格
git地址: https://gitee.com/zhxs_code/spider_python 目前已简单实现可以爬取指定页面的价格(天猫和狗东的都可以),但是由于天猫与狗东对价格的展示方式和策 ...
- django基础之day08,ajax结合sweetalert的使用
models.py文件 from django.db import models class User(models.Model): username=models.CharField(max_len ...
- Real World CTF一日游
今天去感受了长亭举办的RWCTF现场,参加了技术论坛,也学到了很多的知识 比较有印象的就是 智能安全在Web防护中的探索和实践 阿里云安全防护构建的AI架构体系: 基线检测 基础过滤 异常检测 攻击识 ...
- 常见的 由于未调整服务器 ulimit 而引起的内存溢出问题
原文内容来自于LZ(楼主)的印象笔记,如出现排版异常或图片丢失等问题,可查看当前链接:https://app.yinxiang.com/shard/s17/nl/19391737/e3bb62c9-9 ...
- 百万级高并发mongodb集群性能数十倍提升优化实践
背景 线上某集群峰值TPS超过100万/秒左右(主要为写流量,读流量很低),峰值tps几乎已经到达集群上限,同时平均时延也超过100ms,随着读写流量的进一步增加,时延抖动严重影响业务可用性.该集群采 ...
- JavaScript图形实例:合成花卉图
我们知道在直角坐标系中,圆的方程可描述为: X=R*COS(α) Y=R*SIN(α) 用循环依次取α值为0~2π,计算出X和Y,在canvas画布中将坐标点(X,Y)用线连起来,可绘制出一个圆.编写 ...
- leetcode菜鸡斗智斗勇系列(2)--- 把一个ipv4地址转换成一串数字
1.原题: https://leetcode.com/problems/defanging-an-ip-address/ 这道题本身很简单, Given a valid (IPv4) IP addre ...
- javax.servlet.ServletException: Could not resolve view with name 'order/list' in servlet with name 'dispatcherServlet'
javax.servlet.ServletException: Could not resolve view with name 'order/list' in servlet with name ' ...
- Redis学习(二)Redis的安装
Window 下安装 下载地址:https://github.com/MSOpenTech/redis/releases. Redis 支持 32 位和 64 位.这个需要根据你系统平台的实际情况选择 ...