Spring Framework 3.0发布了。这里我们介绍其中的一个:用于格式化的注解。
简介

Spring 3 提供了两个可以用于格式化数字、日期和时间的注解@NumberFormat和@DateTimeFormat,这两个标签可以用于bean的属性或方法参数上。@NumberFormat可以用来格式化任何的数字的基本类型(如int,long)或java.lang.Number的实例(如 BigDecimal, Integer)。@DateTimeFormat可以用来格式化java.util.Date、java.util.Calendar和 java.util.Long类型,也可以用于Joda Time类型的字段或参数。(Joda Time是一个开源的包,提供了对date和time类的一些替代类)。

要指定数字或日期/时间类型的属性,只需要在其上添加 @NumberFormat或@DateTimeFormat注解接可以了。例如下面的代码:

  1. import java.math.BigDecimal;
    import java.util.Calendar;
    import java.util.Date;
    import org.joda.time.LocalTime;
    public class Employee {
    private String name;
    private double salary;
    private double w4AdditionalWithdraw;
    private int dependents;
    private BigDecimal visualAcuity;
    private Date birthDate;
    private Calendar hireDate;
    private LocalTime startTime;
    private long lastTimeEntry;
    /**
    * initialization block to provide sample data for display
    */
    {
    this.name = "John Doe";
    this.salary = 30100.50;
    this.w4AdditionalWithdraw = 0.02;
    this.dependents = 5;
    this.visualAcuity = new BigDecimal(".1");
    Calendar dob = Calendar.getInstance();
    dob.set(1964, Calendar.AUGUST, 30);
    this.birthDate = dob.getTime();
    this.hireDate = Calendar.getInstance();
    this.startTime = new LocalTime(8, 0);
    this.lastTimeEntry = (new Date()).getTime() - 10000;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public double getSalary() {
    return salary;
    }
    public void setSalary(double salary) {
    this.salary = salary;
    }
    public double getW4AdditionalWithdraw() {
    return w4AdditionalWithdraw;
    }
    public void setW4AdditionalWithdraw(double w4AdditionalWithdraw) {
    this.w4AdditionalWithdraw = w4AdditionalWithdraw;
    }
    public int getDependents() {
    return dependents;
    }
    public void setDependents(int dependents) {
    this.dependents = dependents;
    }
    public BigDecimal getVisualAcuity() {
    return visualAcuity;
    }
    public void setVisualAcuity(BigDecimal visualAcuity) {
    this.visualAcuity = visualAcuity;
    }
    public Date getBirthDate() {
    return birthDate;
    }
    public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
    }
    public LocalTime getStartTime() {
    return startTime;
    }
    public void setStartTime(LocalTime startTime) {
    this.startTime = startTime;
    }
    public Calendar getHireDate() {
    return hireDate;
    }
    public void setHireDate(Calendar hireDate) {
    this.hireDate = hireDate;
    }
    public long getLastTimeEntry() {
    return lastTimeEntry;
    }
    public void setLastTimeEntry(long lastTimeEntry) {
    this.lastTimeEntry = lastTimeEntry;
    }
    }
    复制代码

这段代码中我们没有添加注解。如果我们使用Spring 份额Form 标签将这个bean中的数据用于显示的时候,我们会得到类似下图的结果:

可以看到,所有的数据都是以默认的格式显示的,Spring会使用默认的格式将数据显示在HTML表格中(其他的框架也大多如此)。如果想显示特殊的格式,开发人员必须编写特殊的getter/setter方法或使用PropertyEditors来显示特殊格式的数字或者日期/时间。
现在有了 @NumberFormat和@DateTimeFormat注解,我们可以使用这两个注解来完成同样的功能。如下面的代码所示:

  1. import java.math.BigDecimal;
    import java.util.Calendar;
    import java.util.Date;
    import org.joda.time.LocalTime;
    import org.springframework.format.annotation.DateTimeFormat;
    import org.springframework.format.annotation.NumberFormat;
    import org.springframework.format.annotation.DateTimeFormat.ISO;
    import org.springframework.format.annotation.NumberFormat.Style;
    public class Employee {
    private String name;
    /**
    * numeric fields using @NumberFormat annotation for formatting.
    */
    @NumberFormat(style = Style.CURRENCY)
    private double salary;
    @NumberFormat(style = Style.PERCENT)
    private double w4AdditionalWithdraw;
    @NumberFormat
    private int dependents;
    @NumberFormat(pattern = "0.00")
    private BigDecimal visualAcuity;
    /**
    * date and time fields using @DateTimeFormat annotation for formatting.
    */
    @DateTimeFormat(style = "M-")
    private Date birthDate;
    @DateTimeFormat(pattern = "w:yyyy")
    private Calendar hireDate;
    @DateTimeFormat(style = "-S")
    private LocalTime startTime;
    @DateTimeFormat(iso = ISO.DATE_TIME)
    private long lastTimeEntry;
    /**
    * initialization block to provide sample data for display
    */
    {
    this.name = "John Doe";
    this.salary = 30100.50;
    this.w4AdditionalWithdraw = 0.02;
    this.dependents = 5;
    this.visualAcuity = new BigDecimal(".1");
    Calendar dob = Calendar.getInstance();
    dob.set(1964, Calendar.AUGUST, 30);
    this.birthDate = dob.getTime();
    this.hireDate = Calendar.getInstance();
    this.startTime = new LocalTime(8, 0);
    this.lastTimeEntry = (new Date()).getTime() - 10000;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public double getSalary() {
    return salary;
    }
    public void setSalary(double salary) {
    this.salary = salary;
    }
    public double getW4AdditionalWithdraw() {
    return w4AdditionalWithdraw;
    }
    public void setW4AdditionalWithdraw(double w4AdditionalWithdraw) {
    this.w4AdditionalWithdraw = w4AdditionalWithdraw;
    }
    public int getDependents() {
    return dependents;
    }
    public void setDependents(int dependents) {
    this.dependents = dependents;
    }
    public BigDecimal getVisualAcuity() {
    return visualAcuity;
    }
    public void setVisualAcuity(BigDecimal visualAcuity) {
    this.visualAcuity = visualAcuity;
    }
    public Date getBirthDate() {
    return birthDate;
    }
    public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
    }
    public LocalTime getStartTime() {
    return startTime;
    }
    public void setStartTime(LocalTime startTime) {
    this.startTime = startTime;
    }
    public Calendar getHireDate() {
    return hireDate;
    }
    public void setHireDate(Calendar hireDate) {
    this.hireDate = hireDate;
    }
    public long getLastTimeEntry() {
    return lastTimeEntry;
    }
    public void setLastTimeEntry(long lastTimeEntry) {
    this.lastTimeEntry = lastTimeEntry;
    }
    }

复制代码

当在页面上显示的时候,我们会直接得到我们想要的格式,如下图所示:

注解的可选属性
注解的属性决定了@NumberFormat和@DateTimeFormat注解怎样格式化相应的属性。 @NumberFormat注解有两个可选的属性:style和pattern。style属性是一个NumberFormat.Style枚举值,可以是以下的三个值之一:

NumberFormat.Style 枚举值 是否缺省值
NUMBER
CURRENCY
PERCENT

这 3种style的应用我们在上面的代码中都有相应的例子。

具体的style的表现形式是与区域相关的。例如,一个double类型的字段,如果style是CURRENCY,那么在en-us的区域显示的时候前面会加上$,在zh-cn的区域显示的时候前面会加上¥。

如果以上的3中方式无法满足需求,我们可以使用pattern属性来指定特殊的输出格式。Pattern的值要遵循Java标准的numeric formatting pattern。对于@NumberFormat来说缺省的是没有pattern的。

@DateTimeFormat 注解有3个可选的属性:style,pattern和iso。属性style允许我们使用两个字符的字符串来表明怎样格式化日期和时间。第一个字符表明了日期的格式,第二个字符表明了时间的格式。下面的表格中列出了可用的选择以及相应的输出的例子:

描述 字符串值 示例输出
短格式(这是缺省值) SS    8/30/64 11:24 AM
中等格式 MM   Aug 30, 1964 11:24:41 AM
长格式 LL August 30, 1964 11:24:41 AM CDT
完整格式 FF   Sunday, August 30, 1964 11:24:41 AM CDT
使用短横线省略日期或时间 M- Aug 30, 1964

Pattern 属性允许我们使用自定义的日期/时间格式。该属性的值遵循java标准的date/time格式规范。缺省的该属性的值为空,也就是不进行特殊的格式化。

最后,可以使用org.springframework.format.annotation.DateTimeFormat.ISO枚举值来使用ISO标准的日期/时间格式来格式化。下面的表格中列出了可能的值和相应的输出

ISO枚举值 输出
DATE   2000-10-31
TIME   01:30:00.000-05:00(最后的是时区)
DATE_TIME 2000-10-31 01:30:00.000-05:00.
NONE 不进行ISO标准的格式化

使用格式化注解的设置

要使用上面介绍的格式化注解,需要进行如下的配置:

1.下载Spring 3.0的jar包并加入到类路径中。

2. 将下面的配置信息加入到spring bean的XML配置文件中。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <mvc:annotation-driven /> </beans>
解析参数

我们也可以使用这些注解来告诉Spring怎样解析输入的数据。下面的例子显示了怎样使用@DateTimeFormat来解析以ISO格式输入的时间信息:
public String getEmployeesOnTheClock(@DateTimeFormat(iso=ISO.TIME) java.util.Date time) { ... }

Spring格式化注解的更多相关文章

  1. spring(7)--注解式控制器的数据验证、类型转换及格式化

    7.1.简介 在编写可视化界面项目时,我们通常需要对数据进行类型转换.验证及格式化. 一.在Spring3之前,我们使用如下架构进行类型转换.验证及格式化: 流程: ①:类型转换:首先调用Proper ...

  2. SpringMVC的数据格式化-注解驱动的属性格式化

    一.什么是注解驱动的属性格式化? --在bean的属性中设置,SpringMVC处理 方法参数绑定数据.模型数据输出时自动通过注解应用格式化的功能. 二.注解类型 1.DateTimeFormat @ ...

  3. spring+mybatise注解实现

    spring+mybatise注解实现 spring.jpa.database=MYSQL spring.datasource.type=com.alibaba.druid.pool.DruidDat ...

  4. SpringBoot+Spring常用注解总结

    为什么要写这篇文章? 最近看到网上有一篇关于 SpringBoot 常用注解的文章被转载的比较多,我看了文章内容之后属实觉得质量有点低,并且有点会误导没有太多实际使用经验的人(这些人又占据了大多数). ...

  5. Spring MVC注解的一些案列

    1.  spring MVC-annotation(注解)的配置文件ApplicationContext.xml <?xml version="1.0" encoding=& ...

  6. Spring系列之Spring常用注解总结

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...

  7. spring @condition 注解

    spring @condition注解是用来在不同条件下注入不同实现的 demo如下: package com.foreveross.service.weixin.test.condition; im ...

  8. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  9. Spring的注解方式实现AOP

    Spring对AOP的实现提供了很好的支持.下面我们就使用Spring的注解来完成AOP做一个例子. 首先,为了使用Spring的AOP注解功能,必须导入如下几个包.aspectjrt.jar,asp ...

随机推荐

  1. C# SQL查询结果ToDataTable

    作者:卞功鑫 转载请保留:http://www.cnblogs.com/BinBinGo/p/6400944.html 最最常用的SQL 查询的返回结果,插入到DataTable 中 //1 连接字符 ...

  2. Html5——视频标签使用

    video标签: 上面的例子使用一个 Ogg 文件,适用于Firefox.Opera 以及 Chrome 浏览器.要确保适用于 Safari 浏览器,视频文件必须是 MPEG4 类型.video 元素 ...

  3. centos7 真实机安装后没有网卡解决办法

    我们在真实机安装完centos7版本后,会发现没有网卡,只有lo口 因为真实机不同你在虚拟机里面,这个时候我们不能连网,更加不要说配置什么静态ip了 是什么原因呢,是因为有些真实机安装了centos系 ...

  4. jmeter获取token并请求失败Internal authentication failed 400

    jmeter访问token报错400 1.请求token地址 2.运行jmeter报错-run 3.400的意思是: 400(错误请求) 服务器不理解请求的语法. 4.报错信息如下 {"er ...

  5. 【Eclipse】如何在Eclipse中如何自动添加注释和自定义注释风格

    背景简介 丰富的注释和良好的代码规范,对于代码的阅读性和可维护性起着至关重要的作用.几乎每个公司对这的要求还是比较严格的,往往会形成自己的一套编码规范.但是再实施过程中,如果全靠手动完成,不仅效率低下 ...

  6. 【Jmeter自学】badboy使用(三)

    ==================================================================================================== ...

  7. IntelliJ Idea设置Could not autowire. No beans of 'xxx' type found

    1.问题描述 在Idea的spring工程里,经常会遇到Could not autowire. No beans of ‘xxxx’ type found的错误提示.但程序的编译和运行都是没有问题的, ...

  8. python-单元测试unittest

    目录: 1.unittest.TestCase中常用的断言方法 1.1 subTest子测试 1.2 套件测试 1.3 批量测试单个用例 2. 加载器 2.1加载器协议 2.2.执行器 TestRun ...

  9. Docker的概述

    什么是Docker 1.容器技术 在计算机的世界中,容器拥有一段漫长且传奇的历史.容器与管理程序虚拟化(hypervisor virtualization,HV)有所不同,管理程序虚拟化通过中间层将一 ...

  10. JAVA Spring Cloud 注册中心 Eureka 相关配置

    转载至  https://www.cnblogs.com/fangfuhai/p/7070325.html Eureka客户端配置       1.RegistryFetchIntervalSecon ...