SpringBoot i18n 国际化多语言
2018-08-16 本文已影响359人
yellow_han
1、配置文件
spring:
messages:
basename: i18n/messages
cache-second: 3600
encoding: UTF-8
注意点:springboot2.0 cache-seconds改为:cache-second
2、在resource下新建
image.png3、在文件里添加内容
messages.properties:welcome = 欢迎
messages_zh_CN.properties:welcome = 欢迎
messages_en_US.properties:welcome= welcome
#(messages.properties默认文件,当找不到语言的配置的时候,使用该文件进行展示)。
4、封装国际化工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.util.Locale;
@Component
public class LocaleMessage {
@Autowired
private MessageSource messageSource;
/**
* @param code:对应文本配置的key.
* @return 对应地区的语言消息字符串
*/
public String getMessage(String code){
return this.getMessage(code,new Object[]{});
}
public String getMessage(String code,String defaultMessage){
return this.getMessage(code,null,defaultMessage);
}
public String getMessage(String code,String defaultMessage,Locale locale){
return this.getMessage(code,null,defaultMessage,locale);
}
public String getMessage(String code,Locale locale){
return this.getMessage(code,null,"",locale);
}
public String getMessage(String code,Object[] args){
return this.getMessage(code,args,"");
}
public String getMessage(String code,Object[] args,Locale locale){
return this.getMessage(code,args,"",locale);
}
public String getMessage(String code,Object[] args,String defaultMessage){
Locale locale = LocaleContextHolder.getLocale();
return this.getMessage(code,args, defaultMessage,locale);
}
public String getMessage(String code,Object[]args,String defaultMessage,Locale locale){
return messageSource.getMessage(code,args, defaultMessage,locale);
}
}
5、新增controller
import com.stylefeng.guns.core.util.LocaleMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class HelloController {
@Resource
private LocaleMessage localeMessage;
@RequestMapping("/hello")
public String hello(){
System.out.println("1");
String msg3 = localeMessage.getMessage("welcome");
System.out.println(msg3);
return msg3;
}
}