[scala]基于resourcebundle的messagesource


之前写了一篇模拟spring的messagesource实现,后来了解到spring使用的是resourcebundle,于是稍微了解resourcebundle之后改进了实现,可能比以前简化很多。

import java.util.Locale
import java.util.ResourceBundle
import java.util.MissingResourceException
import java.text.MessageFormat

trait MessageSource {

  def getMessage(
    code: String, 
    locale: Locale, 
    args: Array[Any] = Array[Any]()): Option[String]

}

class ResourceBundleMessageSource(codeBase: String) extends MessageSource {

  def getMessage(code: String, locale: Locale, args: Array[Any]) = {
    val bundle = ResourceBundle.getBundle(codeBase, locale)
    getString(bundle, code).map(new MessageFormat(_).format(args))
  }

  private def getString(bundle: ResourceBundle, key: String): Option[String] = {
    try { Some(bundle.getString(key)) } catch {
      case _: MissingResourceException => None
    }
  }

}

object ResourceBundleReader {

  def main(args: Array[String]): Unit = {
    val source = new ResourceBundleMessageSource("messages")
    println(source.getMessage("greeting", Locale.getDefault, Array("XnnYygn")).getOrElse("hello, world!"))
    println(source.getMessage("no_such_message", Locale.getDefault).getOrElse("hello, world!"))
    println(source.getMessage("greeting", Locale.SIMPLIFIED_CHINESE, Array("XnnYygn")).getOrElse("hello, world!"))
  }

}
,