前言

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的更多相关文章

  1. Java国际化(i18n)

    Java国际化(i18n) 最近在做一个网站国际化的功能.用Java做开发,使用spring+velocity. Java提供了对i18n的支持,spring对其做了集成,可以很方便的配置.主要思想就 ...

  2. 国际化支持(I18N)

    本章译者:@nixil 使用国际化支持(I18N)能够使你的应用根据用户所在地区的不同选择不同的语言.下面介绍如何在引用中使用国际化. 只允许使用UTF-8 Play只支持UTF-8一种字符编码.这是 ...

  3. java框架篇---Struts2 本地化/国际化(i18n)

    国际化(i18n)是规划和实施的产品和服务,使他们能很容易地适应特定的本地语言和文化的过程中,这个过程被称为本地化.国际化的过程有时也被称为翻译或本地化启用.国际化是缩写i18n,因为我和两端用n字打 ...

  4. 【转】jQuery之前端国际化jQuery.i18n.properties

    jQuery之前端国际化jQuery.i18n.properties 基于jQuery.i18n.properties 实现前端页面的资源国际化 jquery-i18n-properties

  5. java框架篇---Struts2 本地化/国际化(i18n)(转)

    源地址:https://www.cnblogs.com/oumyye/p/4368453.html 国际化(i18n)是规划和实施的产品和服务,使他们能很容易地适应特定的本地语言和文化的过程中,这个过 ...

  6. [Ruby on Rails系列]4、专题:Rails应用的国际化[i18n]

    1. 什么是internationalization(i18n)? 国际化,英文简称i18n,按照维基百科的定义:国际化是指在设计软件,将软件与特定语言及地区脱钩的过程.当软件被移植到不同的语言及地区 ...

  7. jQuery之前端国际化jQuery.i18n.properties

    jQuery.i18n.properties是一款轻量级的jQuery国际化插件,能实现Web前端的国际化. 国际化英文单词为:Internationalization,又称i18n,"i& ...

  8. Chrome浏览器扩展开发系列之十八:扩展的软件国际化chrome.i18n API

    i18n是internationalization 的简写,这里将讨论软件国际化的问题.熟悉软件国际化的朋友应该知道,软件国际化要求,页面中所有用户可见的字符串都必须置于资源属性文件中.资源属性文件中 ...

  9. jQuery之前端国际化jQuery.i18n.properties[转]

    http://www.ibm.com/developerworks/cn/web/1305_hezj_jqueryi18n/ jQuery.i18n.properties是一款轻量级的jQuery国际 ...

随机推荐

  1. Elasticsearch学习笔记 一

    本文版权归博客园和作者吴双本人共同所有 转载和爬虫请注明原文地址 www.cnblogs.com/tdws. 本文参考和学习资料 <ES权威指南> 一.基本概念 存储数据到ES中的行为叫做 ...

  2. Scrapy框架--Requests对象

    Scrapy使用request对象来爬取web站点. request对象由spiders对象产生,经由Scheduler传送到Downloader,Downloader执行request并返回resp ...

  3. WiFi万能钥匙4.1.32接口

    做Key4WiFi时提取的接口 部分代码来自于 http://zke1ev3n.me/2016/04/06/WiFi%E4%B8%87%E8%83%BD%E9%92%A5%E5%8C%99%E6%8E ...

  4. Prometheus 到底 NB 在哪里?- 每天5分钟玩转 Docker 容器技术(84)

    本节讨论 Prometheus 的核心,多维数据模型.我们先来看一个例子. 比如要监控容器 webapp1 的内存使用情况,最传统和典型的方法是定义一个指标 container_memory_usag ...

  5. EL&&JSTL

    一.JSP技术 1.jsp脚本和注释 jsp脚本: 1)<%java代码%> ----- 内部的java代码翻译到service方法的内部 2)<%=java变量或表达式> - ...

  6. 【面向对象】详解之JavaScript篇

    [重点提前说:面向对象的思想很重要!] 最近开始接触学习后台的PHP语言,在接触到PHP中的面向对象相关思想之后,突然想到之前曾接触的JS中的面向对象思想,无奈记性太差,便去翻了翻资料,花了点时间梳理 ...

  7. LeetCode 252. Meeting Rooms (会议室)$

    Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si ...

  8. JAVA提高九:集合体系

    在经过了前面的JDK6.0新特性的学习后,将进一步深入学习JDK,因为集合的重要性,因此从集合开始入手分析: 一.集合概况 Java是一种面向对象语言,如果我们要针对多个对象进行操作,那么首先必要将多 ...

  9. Vue源码终笔-VNode更新与diff算法初探

    写完这个就差不多了,准备干新项目了. 确实挺不擅长写东西,感觉都是罗列代码写点注释的感觉,这篇就简单阐述一下数据变动时DOM是如何更新的,主要讲解下其中的diff算法. 先来个正常的html模板: & ...

  10. SQL基本查询_多表查询(实验三)

    SQL基本查询_多表查询(实验三) 题目要求(一) 针对emp.dept两表完成如下查询,并验证查询结果的正确性 使用显式内连接查询所有员工的信息,显示其编号.姓名.薪水.入职日期及部门名称: 使用隐 ...