package com.xiaopeng.account.config; import org.springframework.boot.autoconfigure.context.MessageSourceProperties; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.util.StringUtils; import org.springframework.web.servlet.LocaleResolver; import java.nio.charset.StandardCharsets; import java.time.Duration; /** * 国际化配置 */ @Configuration public class MessageLocalConfig { /** * 创建MessageSourceProperties Bean * 配置国际化资源文件的基本属性 */ @Bean public MessageSourceProperties messageSourceProperties() { MessageSourceProperties properties = new MessageSourceProperties(); // 设置资源文件基础名称 properties.setBasename("i18n/messages"); // 设置编码为UTF-8 properties.setEncoding(StandardCharsets.UTF_8); // 不回退到系统默认语言 properties.setFallbackToSystemLocale(false); // 缓存时间设置为-1(永久缓存) properties.setCacheDuration(Duration.ofSeconds(-1)); // 不总是使用MessageFormat properties.setAlwaysUseMessageFormat(false); // 使用消息键作为默认消息 properties.setUseCodeAsDefaultMessage(true); return properties; } @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()); Duration cacheDuration = properties.getCacheDuration(); if (cacheDuration != null) { messageSource.setCacheMillis(cacheDuration.toMillis()); } messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); return messageSource; } @Bean//注册国际化组件 public LocaleResolver localeResolver(){ return new MyLocaleResolver(); } }