SpringBoot读取资源文件

x33g5p2x  于2021-12-06 转载在 Spring  
字(2.5k)|赞(0)|评价(0)|浏览(495)

在Java项目中,资源文件一般都为 *.properties 文件(只能存储key-value格式的数据),SpringMVC中提供有MessageSource接口进行资源文件的读取,在SpringBoot中也支持同样的操作。

读取资源文件

在resources目录下新建i18n文件夹,在文件夹中新建message.properties文件:

title=SpringBoot开发框架
desc=官方网址: https://spring.io/projects/spring-boot

修改application.yml文件,指定资源文件的basename

server:
  port: 8080
spring:
  messages:
    basename: i18n/message

在java对象中注入MessageSource,根据key来读取value值。

@RestController
@RequestMapping("/message/*")
public class MessageAction {
   private final MessageSource messageSource; // 资源文件处理类

   public MessageAction(MessageSource messageSource) {
       this.messageSource = messageSource;
   }

   @RequestMapping("/get")
   public Map<String, Object> getMessage() {
       String title = messageSource.getMessage("title", null, Locale.getDefault());
       String desc = messageSource.getMessage("desc", null, Locale.getDefault());
       Map<String, Object> map = new LinkedHashMap<>();
       map.put("title", title);
       map.put("desc", desc);
       return map;
   }
}

访问http://localhost:8080/message/get

设置国际化

i18n文件夹再定义两个文件,message_zh_CN.propertiesmessage_en_US.properties:

# message_zh_CN.properties
title=SpringBoot开发框架
desc=官方网址: https://spring.io/projects/spring-boot
# message_en_US.properties
title=SpringBoot Development framework
desc=Official website: https://spring.io/projects/spring-boot

如果想要设置国际化,那么就不能使用默认的Locale,可以实现一个Locale解析器,通过传入字符串的方式指定Locale。

定义一个DefaultLocaleResolver,并在Spring容器中提供实例对象。

@Configuration
public class DefaultLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String loc = request.getParameter("loc"); // 取得请求参数
        if (!StringUtils.hasLength(loc)) {
            return Locale.getDefault(); // 设置默认Locale
        }
        String[] localeArray = loc.split("_");
        return new Locale(localeArray[0], localeArray[1]); // 采用传入的locale
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {}

    @Bean(name="localeResolver") // 指定LocaleResolver名称,否则可能不生效
    public LocaleResolver getLocaleResolver() {
        return new DefaultLocaleResolver();
    }
}

修改控制器,在方法参数里面接收Locale对象,该Locale对象正是采用DefaultLocaleResolver生成的。

@RequestMapping("/get")
public Map<String, Object> getMessage(Locale locale) {
    String title = messageSource.getMessage("title", null, locale);
    String desc = messageSource.getMessage("desc", null, locale);
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("title", title);
    map.put("desc", desc);
    return map;
}

此时输入http://localhost:8080/message/get?loc=zh_CN可以得到中文版本:

输入http://localhost:8080/message/get?loc=en_US则可以得到英文版本:

相关文章

微信公众号

最新文章

更多