SpringBoot 官方文档示例:(44)spring boot 国际化
原创
©著作权归作者所有:来自51CTO博客作者wx62e0d796b5814的原创作品,请联系作者获取转载授权,否则将追究法律责任
一、国际化的含义:根据当前的语言环境,从资源文件中读取和该语言环境匹配的属性值。
中文环境,默认会读取resources下messages.properties和messages_zh_CN.properties中的值
二、messages_zh_CN.properties
welcome的值为中文你好加上传入的第1个参数
三、通过ApplicationContextAware来获取资源文件中的值
package cn.edu.tju.service;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.Locale;
@Service
public class BasicService implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
public String getInfo(String str,String[] args){
String result=applicationContext.getMessage(str,args, Locale.getDefault());
return result;
}
}
四、在控制器中注入上述service,并调用getInfo方法来获取资源文件中的属性
package cn.edu.tju.controller;
import cn.edu.tju.service.BasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController2 {
@Autowired
private BasicService basicService;
@RequestMapping("/test")
public String getMessage(){
String result=basicService.getInfo("welcome",new String[]{"中国"});
return result;
}
}
五、启动程序,访问/test接口,会返回"你好中国"
六、如果不想使用默认的资源文件,比如想使用lab.properties加lab_zh_CN.properties,
则需要在application.properties中配置:
spring.messages.basename=lab