使用dropwizard(6)-国际化-easy-i18n


前言
Dropwizard官方文档并没有提供国际化的模块,所以只能自己加。Spring的MessageResource用的很顺手,所以copy过来。
Easy i18n
在整合Dropwizard的时候,多语言貌似只能通过jdk自带的ResourceBundle拿数据。其实也就够了,但在开发过程中发现需要缓存,需要解析占位符等。代码越写越多,显然不是仅仅一个调用就完事的。写的差不多的时候突然觉得和spring context里的message source结构类似。于是,放弃维护已经开始变的复杂的逻辑,直接使用spring。
但选取dropwizard的时候就是摒弃了spring,再拿过来也不好玩了。干脆,抽取Spring context项目的MessageResource相关代码,重写封装了一个library: https://github.com/Ryan-Miao/easy-i18n, 欢迎star。
easy-i18n还是和在Spring项目中相同。
首先,引入依赖,由于github项目的library已经有仓库去维护了,就没费心思放到maven和jcenter了,直接从github上拉取。类库地址为:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
引入
<dependency>
<groupId>com.github.Ryan-Miao</groupId>
<artifactId>easy-i18n</artifactId>
<version>1.0</version>
</dependency>
简单使用
#情形一 只有一个Resource Bundle
在resources下新建i18n/messages.properties以及i18n/messages_zh_CN.properties. demo位置:l4dropwizard
然后,调用方法如下:
@Test
public void testI18n(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.addBasenames("i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
String index = messageSource.getMessage("index", null, Locale.US);
System.out.println(index);
}
#情形二 我有多个Resource Bundle
实际项目中,由于产品分类,有时候需要创建多个Resource Bundle,这时候也简单,只要创建多个ResourceBundleMessageSource来读取翻译即可。
public void testI18n2(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.addBasenames("i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
String index = messageSource.getMessage("index", null, Locale.US);
System.out.println(index);
ResourceBundleMessageSource messageSource2 = new ResourceBundleMessageSource();
messageSource.addBasenames("i18n/messages2");
messageSource.setDefaultEncoding("UTF-8");
String second = messageSource.getMessage("second", null, Locale.US);
System.out.println(second);
}
#情形三 我有多个Resource Bundle但读取翻译的时候我想一起
有时候,想要读取翻译,可能翻译文件在不同的Resource Bundle,但我指向用一个接口去调用。这时候,做法时候在这几个Resource Bundle的里面添加命名空间,即key要在这几个Resource Bundle里唯一,而不仅仅是本文件唯一。
然后,
public void testI18n2(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.addBasenames("i18n/messages", "i18n/messages2");
messageSource.setDefaultEncoding("UTF-8");
String index = messageSource.getMessage("index", null, Locale.US);
System.out.println(index);
}
这种做法,会一次从两个Resource Bundle里寻找翻译,找到即返回。因此,如果有相同的key,将导致只有第一个生效。
#情形4
没有了,你翻译要那么复杂吗。
更多用法,参考测试类:ResourceBundleMessageSourceTest
Demo source
https://github.com/Ryan-Miao/l4dropwizard
本文是基于dropwizard入门之上的演进。
确保依赖都是最新的,或者自行解决版本冲突,比如jackson不同版本之间的类有所不同。
引入easy-i18n
repository url
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
引入
<dependency>
<groupId>com.github.Ryan-Miao</groupId>
<artifactId>easy-i18n</artifactId>
<version>1.0</version>
</dependency>
添加Resource Bundle
在resources下新增文件夹i18n, 依次添加几个Resource Bundle。具体做法是,在文件夹i18n右键 -> new -> Resource Bundle, 然后选择想要支持的语言。比如美国en_US,简体中文zh_CN。
新建MessageService
创建一个Util来处理翻译功能。
com.test.domain.service.IMessageService
package com.test.domain.service;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
/**
* The Message translation service
* Created by Ryan Miao on 11/23/17.
*/
public interface IMessageService {
/**
* Get translation by message key.
*
* @param key The message key in the properties
* @return the translated message
*/
String getMessage(String key, Locale locale);
/**
* Get translation by message key and compose it with variables.
* Note that the variable would be injected by {@link MessageFormat}
*
* @param key The message key in the properties
* @param args The variables to inject into the message.
* @return the translated message.
*/
String getMessage(String key, List<String> args, Locale locale);
}
实现类com.test.domain.service.impl.MessageService
package com.test.domain.service.impl;
import com.miao.easyi18n.support.ResourceBundleMessageSource;
import com.test.domain.service.IMessageService;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Locale;
/**
* Created by Ryan Miao on 11/23/17.
*/
@Singleton
public class MessageService implements IMessageService{
private final ResourceBundleMessageSource messageSource;
@Inject
public MessageService(ResourceBundleMessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public String getMessage(String key, Locale locale) {
return messageSource.getMessage(key, null, locale);
}
@Override
public String getMessage(String key, List<String> args, Locale locale) {
return messageSource.getMessage(key, args.toArray(), locale);
}
}
在IoC中提供ResourceBundleMessageSource
由于ResourceBundleMessageSource是公共组件,需要单独提取出来,并使用单例模式创建。关于IoC的配置,参阅dropwizard中添加DI
在ConfigurationModule中:
package com.test.domain.ioc.module;
import com.miao.easyi18n.support.ResourceBundleMessageSource;
import com.test.configuration.HelloWorldConfiguration;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/**
* Created by Ryan Miao on 11/20/17.
*/
@Module
public class ConfigurationModule {
private final HelloWorldConfiguration configuration;
public ConfigurationModule(HelloWorldConfiguration configuration) {
this.configuration = configuration;
}
@Provides
@Singleton
HelloWorldConfiguration helloWorldConfiguration(){
return configuration;
}
@Singleton
@Provides
ResourceBundleMessageSource resourceBundleMessageSource(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.addBasenames("i18n/messages", "i18n/messages2", "i18n/otherGroup");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
这里,关于Resource Bundle的位置没有单独提出来,后面可以放到HelloWorldConfiguration,提到配置文件中。
测试
在dagger中,接口和实现类的绑定只能通过手动声明。因此,绑定IMessageService
@Singleton
@Provides
IMessageService messageService(MessageService messageService){
return messageService;
}
创建测试Resource, com.test.domain.resource.LocalResource
package com.test.domain.resource;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;
import com.test.domain.entiry.GithubUser;
import com.test.domain.service.IMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Locale;
import java.util.Map;
/**
* Test localization
* Created by Ryan Miao on 11/23/17.
*/
@Api("/local")
@Path("/local")
@Produces(MediaType.APPLICATION_JSON)
public class LocalResource {
private final IMessageService messageService;
@Inject
public LocalResource(IMessageService messageService) {
this.messageService = messageService;
}
@GET
@Timed
@Path("/{key}")
@ApiOperation(value = "Get github user profile.", notes = "There should be the note.")
@ApiResponses({
@ApiResponse(code = 401, message = "Valid credentials are required to access this resource."),
@ApiResponse(code = 400, message = "Params not valid."),
@ApiResponse(code = 500, message = "Something wrong from the server."),
@ApiResponse(code = 200, message = "Success.", response = GithubUser.class)
})
public Map<String, String> getIndex(
@PathParam("key") final String index,
@HeaderParam("Accept-Language") @Valid
@NotNull(message = "cannot be null.")
@Pattern(regexp = "([a-z]{2}-[A-Z]{2})", message = "pattern should like zh-CN, en-US.")
final String language
) {
final Locale locale = Locale.forLanguageTag(language);
final String message = messageService.getMessage(index, locale);
return ImmutableMap.of(index, message);
}
}
结果


使用dropwizard(6)-国际化-easy-i18n的更多相关文章
- Java国际化(i18n)
Java国际化(i18n) 最近在做一个网站国际化的功能.用Java做开发,使用spring+velocity. Java提供了对i18n的支持,spring对其做了集成,可以很方便的配置.主要思想就 ...
- 国际化支持(I18N)
本章译者:@nixil 使用国际化支持(I18N)能够使你的应用根据用户所在地区的不同选择不同的语言.下面介绍如何在引用中使用国际化. 只允许使用UTF-8 Play只支持UTF-8一种字符编码.这是 ...
- java框架篇---Struts2 本地化/国际化(i18n)
国际化(i18n)是规划和实施的产品和服务,使他们能很容易地适应特定的本地语言和文化的过程中,这个过程被称为本地化.国际化的过程有时也被称为翻译或本地化启用.国际化是缩写i18n,因为我和两端用n字打 ...
- 【转】jQuery之前端国际化jQuery.i18n.properties
jQuery之前端国际化jQuery.i18n.properties 基于jQuery.i18n.properties 实现前端页面的资源国际化 jquery-i18n-properties
- java框架篇---Struts2 本地化/国际化(i18n)(转)
源地址:https://www.cnblogs.com/oumyye/p/4368453.html 国际化(i18n)是规划和实施的产品和服务,使他们能很容易地适应特定的本地语言和文化的过程中,这个过 ...
- [Ruby on Rails系列]4、专题:Rails应用的国际化[i18n]
1. 什么是internationalization(i18n)? 国际化,英文简称i18n,按照维基百科的定义:国际化是指在设计软件,将软件与特定语言及地区脱钩的过程.当软件被移植到不同的语言及地区 ...
- jQuery之前端国际化jQuery.i18n.properties
jQuery.i18n.properties是一款轻量级的jQuery国际化插件,能实现Web前端的国际化. 国际化英文单词为:Internationalization,又称i18n,"i& ...
- Chrome浏览器扩展开发系列之十八:扩展的软件国际化chrome.i18n API
i18n是internationalization 的简写,这里将讨论软件国际化的问题.熟悉软件国际化的朋友应该知道,软件国际化要求,页面中所有用户可见的字符串都必须置于资源属性文件中.资源属性文件中 ...
- jQuery之前端国际化jQuery.i18n.properties[转]
http://www.ibm.com/developerworks/cn/web/1305_hezj_jqueryi18n/ jQuery.i18n.properties是一款轻量级的jQuery国际 ...
随机推荐
- 【学习】如何用jQuery获取iframe中的元素
(我的博客网站中的原文:http://www.xiaoxianworld.com/archives/292,欢迎遇到的小伙伴常来瞅瞅,给点评论和建议,有错误和不足,也请指出.) 说实在的,以前真的很少 ...
- win10 uwp 绑定静态属性
Jasoon 大神问,如何绑定静态属性. 我们经常有静态属性,那么我们如何绑定 假如我们的ViewModel有一个静态属性 public static string CVTE { set; get; ...
- 使用Hexo+Github一步步搭建属于自己的博客(基础)
前言:电脑系统为window 10专业版,64位 相关步骤: 1.安装Node.js和配置好Node.js环境,打开cmd命令行,成功界面如下 2.安装Git和配置好Git环境,安装成功的象征就是在电 ...
- uva 10118,记忆化搜索
这个题debug了长达3个小时,acm我不能放弃,我又回来了的第一题! 一开始思路正确,写法不行,结果越改越乱 看了网上某神的代码,学习了一下 coding+debug:4小时左右,记忆化搜索+dp类 ...
- (扩展根目录容量方法汇总)把Linux系统迁移到另一个分区或者硬盘
Linux系统扩容方法汇总 相信很多朋友都有过这样的经历,本想装个Ubantu玩玩,没想到玩久了反而不习惯Windows了,然而开始装系统的时候只分配了非常小的空间,那应该怎样扩展我们的ubantu呢 ...
- ELK系列~Nxlog日志收集加转发(解决log4日志换行导致json转换失败问题)
本文章将会继承上一篇文章,主要讲通过工具来进行日志的收集与发送,<ELK系列~NLog.Targets.Fluentd到达如何通过tcp发到fluentd> Nxlog是一个日志收集工具, ...
- 使用bitset实现毫秒级查询(二)
在上一篇中我们了解了bitset索引的基本用法,本篇开始学习bitset索引更新及一些复杂查询. 1.bitset索引更新 因为我们的数据是在系统启动时全部加载进内存,所以当数据库数据发生变化时要 ...
- HDFS 简介
hadoop分别从3个角度将主机划分为2种角色 最基本的是Master 和 从HDFS角度,将主机划分为namenode和datanode,在分布式文件系统中,目录管理很重要,管理目录相当于主人 从m ...
- Loadrunner Http接口Get/Post方法性能测试脚本解析
最近使用LoadRunner 11进行了一次完整的Http WEB接口性能测试,下面介绍下Http接口Get/Post方法性能测试脚本通用编写方法. 1. Http接口性能测试基本流程 首先定义了一个 ...
- swift之函数式编程(五)
文章内容来源于<Functional Programing in Swift>,详情请看原著 The Value of Immutability swift 对于控制值改变有一些机制.在这 ...