使用dropwizard(6)-国际化-easy-i18n
来源:互联网 发布:当爱已成往事 知乎 编辑:程序博客网 时间:2024/06/06 01:32
前言
Dropwizard官方文档并没有提供国际化的模块,所以只能自己加。Spring的MessageResource用的很顺手,所以copy过来。
作者:@Ryan-Miao
本文为作者原创,转载请注明出处:http://www.cnblogs.com/woshimrf/p/dropwizard-i18n.html
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
然后,调用方法如下:
@Testpublic 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(); messageSource2.addBasenames("i18n/messages2"); messageSource2.setDefaultEncoding("UTF-8"); String second = messageSource2.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. */@Singletonpublic 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. */@Modulepublic 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@ProvidesIMessageService 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
- 使用i18n实现页面国际化
- 国际化--i18n
- 国际化-I18n
- 国际化i18n
- 国际化(I18N)
- I18N国际化
- 国际化i18n
- 国际化(i18n)
- 国际化(i18n)
- 国际化(i18n)
- 国际化i18n
- 在struts中使用国际化(i18n)
- 使用js模拟i18n国际化的例子
- js国际化解决方案(使用 jQuery.i18n.properties)
- Java 6 : 自定义国际化(I18N)服务
- Dropwizard使用错误汇总
- 在struts中完美的使用i18n-国际化原来如此简单
- 二叉树最简单构成
- javascript函数之arguments学习
- Android Activity的launchMode四种启动模式备忘
- Ansible常见模块与使用方法
- PTA修理牧场
- 使用dropwizard(6)-国际化-easy-i18n
- Java枚举类
- Time.deltaTime 的含义用法
- JavaAPI编译转换接口CompilationTask的Call()方法翻译
- ICP算法(Iterative Closest Point迭代最近点算法)
- openstack 备份 backup之chunkeddriver源码解读
- 【ZJOI2014】【BZOJ3527】 力 (FFT)
- 160
- 数列特征