<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>sping boot &#8211; 有意与无意之间</title>
	<atom:link href="https://zhangxihai.cn/archives/tag/sping-boot/feed" rel="self" type="application/rss+xml" />
	<link>https://zhangxihai.cn</link>
	<description>千淘万漉虽辛苦 吹尽狂沙始到金 - 生命不息 编程不止</description>
	<lastBuildDate>Tue, 31 Oct 2023 10:23:06 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.11</generator>
	<item>
		<title>Spring boot基础: 国际化</title>
		<link>https://zhangxihai.cn/archives/249</link>
					<comments>https://zhangxihai.cn/archives/249#respond</comments>
		
		<dc:creator><![CDATA[胖爷]]></dc:creator>
		<pubDate>Tue, 19 Jun 2018 10:21:34 +0000</pubDate>
				<category><![CDATA[编码]]></category>
		<category><![CDATA[sping boot]]></category>
		<category><![CDATA[国际化]]></category>
		<guid isPermaLink="false">https://zhangxihai.cn/?p=249</guid>

					<description><![CDATA[在Spring Boot中，国际化是通过MessageSource和LocalResolver两个核心接口来实现。 Spring Boot提供了自动配置类来简化国际化的配置，其中最重要的配置类是MessageSourceAutoConfiguration和 LocaleCharsetMappingAutoConfiguration。 MessageSourc...]]></description>
										<content:encoded><![CDATA[<p>在Spring Boot中，国际化是通过<code>MessageSource</code>和<code>LocalResolver</code>两个核心接口来实现。</p>
<p>Spring Boot提供了自动配置类来简化国际化的配置，其中最重要的配置类是<code>MessageSourceAutoConfiguration</code>和<code> LocaleCharsetMappingAutoConfiguration</code>。</p>
<p><code>MessageSourceAutoConfiguration</code>是一个关键的自动配置类，用于配置<code>MessageSource</code></p>
<pre><code> @Configuration
@ConditionalOnMissingBean(MessageSource.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(prefix = "spring.messages", name = "basename")
public class MessageSourceAutoConfiguration {

    @Bean
    public MessageSource messageSource(MessageSourceProperties properties) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
                    StringUtils.trimAllWhitespace(properties.getBasename()));
        }
        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }
        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        messageSource.setCacheMillis(properties.getCacheMillis());
        return messageSource;
    }

    @Configuration
    @ConditionalOnNotWebApplication
    static class BaseConfiguration {

        @Bean
        public static MessageSourceInitializer messageSourceInitializer() {
            return new MessageSourceInitializer();
        }

    }

    @Configuration
    @ConditionalOnWebApplication
    static class WebConfiguration {

        @Bean
        public MessageSourceInitializer messageSourceInitializer() {
            return new MessageSourceInitializer();
        }

    }

}</code></pre>
<p>以上代码主要注册了一个<code>MessageSource</code>的实例，通过一些列的<code>spring.messages.*</code>参数就可以完成自动配置。</p>
<p>在<code>MessageSourceProperties</code>中包含以下几个重要的参数：</p>
<pre><code> // 要扫描的国际化文件名，默认为messages, 即在resources资源目录下建立<code>message_xx.properties</code>资源文件，可以通过逗号指定多个，如果不指定包名，则默认classpath跟目录下搜索
 private String basename = "messages";

 // 编码  默认为UTF8
 private Charset encoding = StandardCharsets.UTF_8;

 // 国际化资源文件被加载后的缓存时间，默认单位为秒，如果不指定则为永久缓存
 @DurationUnit(ChronoUnit.SECONDS)
 private Duration cacheDuration;

 // 找不到当前语言的资源文件时是否降级为当前操作系统的语言对应的资源文件，默认为true.  例如无法加载中文语言包<code>messages_zh_CN.properties</code>, 则加载系统默认的文件<code>messages.properties</code>
 private boolean fallbackToSystemLocate = true;
</code></pre>
<h4>配置使用国际化</h4>
<p>国际化支持包含在了spring boot自动配置核心包中了，所以不需要单独引入， 引入spring boot web包即可</p>
<p>```<br />
&lt;dependency&gt;<br />
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br />
&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br />
&lt;/dependency&gt;<br />
&lt;dependency&gt;<br />
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br />
&lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;<br />
&lt;/dependency&gt;<br />
```</p>
<p>&lt;p&gt;&#x60;application.yml&#x60;配置：<br />
```<br />
spring:<br />
messages:<br />
basename: langs/common, langs/index<br />
mvc:<br />
locale: zh_CN<br />
```</p>
<p>&lt;p&gt;文件目录:&lt;/p&gt;<br />
&lt;p&gt;&#x60;&#x60;&#x60;<br />
resources:<br />
langs:<br />
common.properties<br />
common_zh_CN.properties<br />
index.properties<br />
index_zh_CN.propertites<br />
```<br />
themeleaf模板引入</p>
<p>```<br />
&lt;title th:text=&quot;#{title}&quot;&gt;&lt;/title&gt;<br />
...<br />
&lt;span th:text=&quot;#{index.wecome}&quot;&gt;&lt;/span&gt;<br />
```</p>
<p>代码中使用：</p>
<pre><code>@Controller
public class IndeController {
    @Autowired
    private MessageSource messageSource;

    @GetMapping("/wecome")
    public String wecome() {
        return messageSource.getMessage("index.wecome", null, LocaleContextHolder.getLocale());
    }
}</code></pre>
<h4>切换国际化</h4>
<p>根据选择的语言进行切换， 注册一个LocaleResolver区域解析器和区域拦截器：</p>
<pre><code> @Slf4j
 @Configuration
 public class WebConfig implements WebMvcConfigurer {
      /**
       * Locale 默认设置为英文
       * @return
       */
     @Bean
     public LocaleResolver localeResolver() {
         SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
         sessionLocaleResolver.setDefaultLocale(Locale.US);
         return sessionLocaleResolver;
     }

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

     private LocaleChangeInterceptor localeChangeInterceptor() { 
         LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
         localeChangeInterceptor.setParamName("lang");
         return localeChangeInterceptor;
     }
 }</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zhangxihai.cn/archives/249/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
