SpringBoot 国际化
本篇文章主要介绍SpringBoot国际化配置内容。如果文章中有错误或不明确的地方,请大家望指正,谢谢! 链接地址:https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/html/spring-boot-features.html#boot-features-internationalization
国际化配置
application.yaml(basename值为messages时,可以不配置basename)
spring: messages: basename: messages fallback-to-system-locale: false
resources目录下创建国际化文件(必须位于classpath下且后缀名.properties,不然无法加载)
messages.properties(空文件,但该文件必须存在)
messages_zh_CN.properties
greet=\u60A8\u597D
messages_en.properties
greet=hello
HelloWorldController.java
package com.stone.springboot.study; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { @Autowired MessageSource messageSource; @GetMapping("greet") public String greet() { String code = "greet"; return messageSource.getMessage(code, null, LocaleContextHolder.getLocale()); } }
启动项目,访问:http://127.0.0.1:8080/greet
浏览器页面输出:
您好
浏览器-设置-语言 修改为engish
再次访问:http://127.0.0.1:8080/greet
hello
国际化配置属性(MessageSourceProperties)
- basename 可以指定多个用逗号分隔, 默认值:messages
- encoding 指定国际化字符编码,默认编码UTF-8
- cacheDuration
- fallbackToSystemLocale 默认:true; 找不到对应属性值时,查找系统语言对应的属性值;如果设置为false,找不到时,会从默认的配置中查找(messages.properties)
- alwaysUseMessageFormat 默认:false; 是否使用MessageFormat , messageSource.getMessage(code, null, LocaleContextHolder.getLocale()),可以传递参数值.
- useCodeAsDefaultMessage 默认:false; 找不到对应属性值时,把编码当做值返回。建议只在开发环境中使用
总结
国际化配置相对简单,由于现在项目更多的是前后端分离模式,文章中只描述了后台直接返回国际化消息。页面的调用是通过标签直接引用,就不再做描述
浙公网安备 33010602011771号