Spring Boot国际化MessageSource使用

资源文件配置

resources/i18n/Messages.properties

1
2
welcome.url=www.appblog.cn
welcome.msg=欢迎 {0} 光临!

resources/i18n/Messages_zh.properties

1
2
welcome.url=www.appblog.cn
welcome.msg=欢迎 {0} 光临!

resources/i18n/Messages_en.properties

1
2
welcome.url=www.appblog.cn
welcome.msg=Welcome {0}!

application.properties中配置资源文件路径

1
2
#资源文件的名称
spring.messages.basename=i18n/Messages,i18n/Pages

AbstractBaseController–资源文件messages读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public abstract class AbstractBaseController {

@Resource
private MessageSource messageSource;

public String getMessage(String key, String ...args) {
return this.messageSource.getMessage(key, args, Locale.getDefault());
}

public String getMessage(String key, Locale locale, String ...args) {
return this.messageSource.getMessage(key, args, locale);
}

}

资源文件配置使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
public class MessageController extends AbstractBaseController {

@GetMapping("/echo")
public String echo(String name) {
System.out.println("[***访问地址***]: " + super.getMessage("welcome.url"));
return super.getMessage("welcome.msg", name);
}

@GetMapping("/echo/{locale}")
public String echo(@PathVariable("locale") String locale, String name) {
System.out.println("[***访问地址***]: " + super.getMessage("welcome.url", new Locale(locale)));
return super.getMessage("welcome.msg", new Locale(locale), name);
}

}

测试

访问:http://127.0.0.1:8080/echo?name=Joe.Ye,返回:欢迎 Joe.Ye 光临!
访问:http://127.0.0.1:8080/echo/zh?name=Joe.Ye,返回:欢迎 Joe.Ye 光临!
访问:http://127.0.0.1:8080/echo/en?name=Joe.Ye,返回:Welcome Joe.Ye!

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :