1. 程式人生 > >SpringBoot i18n 國際化多語言

SpringBoot i18n 國際化多語言

#1、配置檔案 ``` spring:   messages:     basename: i18n/messages     cache-second: 3600     encoding: UTF-8 ``` #注意點:springboot2.0 cache-seconds改為:cache-second #2、在resource下新建 ![image.png](https://upload-images.jianshu.io/upload_images/13498144-bff10ca1eff92c98.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #3、在檔案裡新增內容 ``` 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;

    } } ``` #6、瀏覽器上測試。