返回介绍

6.3 用 Registrar 注册 Formatter

发布于 2025-04-22 20:10:00 字数 2455 浏览 0 评论 0 收藏

注册 Formatter 的另一种方法是使用 Registrar。例如,清单 6.7 就是注册 DateFormatter 的一个例子。

清单 6.7 MyFormatterRegistrar 类

package formatter;
import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry;

public class MyFormatterRegistrar implements FormatterRegistrar {

  private String datePattern;
  public MyFormatterRegistrar(String datePattern) {
    this.datePattern = datePattern;
  }

  @Override
  public void registerFormatters(FormatterRegistry registry) {
    registry.addFormatter(new LocalDateFormatter(datePattern));
    // register more formatters here
  }
}

有了 Registrar,就不需要在 Spring MVC 配置文件中注册任何 Formatter 了,只在 Spring 配置文件中注册 Registrar 就可以了,如清单 6.8 所示。

清单 6.8 在 springmvc-config.xml 文件中注册 Registrar

< ?xml version="1.0" encoding="UTF-8"?>
< beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/springcontext.xsd">

  < context:component-scan base-package="controller" />
  < context:component-scan base-package="formatter" />

  < mvc:annotation-driven conversion-service="conversionService" /> < mvc:resources mapping="/css/ **" location="/css/" /> < mvc:resources mapping="/ *.html" location="/" /> < bean id="viewResolver" class="org.springframework.web.servlet.view. →InternalResourceViewResolver"> < property name="prefix" value="/WEB-INF/jsp/" /> < property name="suffix" value=".jsp" /> < /bean> < bean id="conversionService" class="org.springframework.format.support. →FormattingConversionServiceFactoryBean"> < property name="formatterRegistrars"> < set> < bean class="formatter.MyFormatterRegistrar"> < constructor-arg type="java.lang.String" value="MM-dd-yyyy" /> < /bean> < /set> < /property> < /bean> < /beans>

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。