Spring3.0的基于注解的MVC非常好用,特别在加入了新的mvc的命名空间后,极大的减少了配置文件内容。但是如果想更改默认DefaultAnnotationHandlerMapping的属性,比如 useDefaultSuffixPattern,alwaysUseFullPath之类的,就会遇到Controller被加载2次,即实例化2次 DefaultAnnotationHandlerMapping对象,这个比较郁闷,因为你更改的属性并没有 生效。
奇怪的是这个问题在spring的官方论坛被提及过(http://forum.springsource.org/showthread.php?t=81238 ), 不过相关问题都被关闭了( https://jira.springsource.org/browse/SPR-6524 )。唯一可行的更改 DefaultAnnotationHandlerMapping 属性的 方法是打散<mvc:annotation-driven> 配置,也就是得了解一下这句配置究竟替换了未定义mvc namespace之前的配置方法( https://jira.springsource.org/browse/SPR-6306 ):
AFTER MVC NAMESPACE
<?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-3.0.xsd">
<mvc:annotation-driven/>
</beans>
BEFORE MVC NAMESPACE
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.0.xsd">
<!-- HANDLER MAPPING RULES -->
<!-- Maps requests to @Controllers based on @RequestMapping("path") annotation values
If no annotation-based path mapping is found, Spring MVC sends a 404 response and logs a pageNotFound warning. -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="1" />
</bean>
<!-- REGISTERED HANDLER TYPES -->
<!-- Enables annotated @Controllers; responsible for invoking an annotated POJO @Controller when one is mapped. -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<!-- Configures Spring MVC DataBinder instances globally -->
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
<property name="validator" ref="validator" />
</bean>
</property>
</bean>
<!-- FIELD TYPE CONVERSION AND VALIDATION -->
<!-- Enables the Spring 3 Type Conversion system that uses Joda Time Formatting for Date/Time types -->
<bean id="conversionService" class="org.springframework.samples.petclinic.util.PetclinicConversionServiceFactory" />
<!-- Configures JSR-303 Declarative Validation with default provider on classpath (Hibernate Validator) -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</beans>