Category: Scala

  • [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]…

  • [scala]spring messagesource的功能模仿实现

    原理 遍历目录下messages*.properties文件 从文件名中取出locale,比如messages_en_US.properties中en和US分别为语言名和国家名 解析properties文件的k=v键值对,有等号,k和v不为空的情况下构造一个Map,k其实为messageCode, v为messageFormat 最后是根据locale和messageCode查询messageFormat 由于scala有强大的option,flatMap等方法,spring的messageSource的defaultMessage作为调用者的可选项,即Option.getOrElse,参照代码最下方的示例 测试结果 Some(Hello, XnnYygn!) Some(Hello, XnnYygn!!!) Some(你好,XnnYygn!) default message

  • [scala]50行实现web表单验证器

    思路是这样,每个表单实现Validatable特质。这个特质要求实现返回一个属性名到验证器列表的映射。 表单验证器执行时首先获取表单所有的属性(除去class),然后遍历这个映射,运行字段对应的验证器变成响应的验证错误(如果有的话),否则最后是个空集合。 FormValidatorRunner(代码最下方)是测试类,执行结果是 Map(name -> List(ValidateError(default.notBlank,List()))) 代码如下:

  • GetBeanProperties via Scala

    一个简单的用Scala写的获取bean属性的例子。核心方法是Introspector#getBean(Class)。 import java.beans.Introspector object GetBeanProperties { class Person(id: Long, name: String) { def getId = id def getName = name } def main(args: Array[String]): Unit = { println(GetBeanProperties(null)) println(GetBeanProperties(new Person(1L, “xnnyygn”))) } def apply[T](bean: T): Map[String, Any] = Option(bean) match { case None => Map[String, Any]() case _ => doApply(bean) } private def doApply[T](bean: T):…