Spring MVC 轉(zhuǎn)換與格式化

2018-07-26 14:50 更新

數(shù)字的Number類型和日期Date類型的格式化是默認安裝了的,包括@NumberFormat注解和@DateTimeFormat注解。如果classpath路徑下存在Joda Time依賴,那么完美支持Joda Time的時間格式化庫也會被安裝好。如果要注冊定制的格式化器或轉(zhuǎn)換器,請覆寫addFormatters方法:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // Add formatters and/or converters
    }

}

使用MVC命名空間時,<mvc:annotation-driven>也會進行同樣的默認配置。要注冊定制的格式化器和轉(zhuǎn)換器,只需要提供一個轉(zhuǎn)換服務(wù)ConversionService

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">

    <mvc:annotation-driven conversion-service="conversionService"/>

    <bean id="conversionService"
            class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="org.example.MyConverter"/>
            </set>
        </property>
        <property name="formatters">
            <set>
                <bean class="org.example.MyFormatter"/>
                <bean class="org.example.MyAnnotationFormatterFactory"/>
            </set>
        </property>
        <property name="formatterRegistrars">
            <set>
                <bean class="org.example.MyFormatterRegistrar"/>
            </set>
        </property>
    </bean>

</beans>

關(guān)于如何使用格式化管理器FormatterRegistrar,請參考 8.6.4 FormatterRegistrar SPI一節(jié),以及FormattingConversionServiceFactoryBean的文檔。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號