`
younglibin
  • 浏览: 1194888 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用 Spring 2.5 注释驱动的 IoC 功能

 
阅读更多

原文地址:

http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/

 

http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/

 

写道
概述
注释配置相对于 XML 配置具有很多的优势:
它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO 的属性名、类型等信息,如果关系表字段和 PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过 Java 反射机制获取。
注释和 Java 代码位于一个文件中,而 XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和 Java 代码放在一起,有助于增强程序的内聚性。而采用独立的 XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
因此在很多情况下,注释配置比 XML 配置更受欢迎,注释配置有进一步流行的趋势。Spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分 XML 配置的功能。在这篇文章里,我们将向您讲述使用注释进行 Bean 定义和依赖注入的内容。
回页首
原来我们是怎么做的
在使用注释配置之前,先来回顾一下传统上是如何配置 Bean 并完成 Bean 之间依赖关系的建立。下面是 3 个类,它们分别是 Office、Car 和 Boss,这 3 个类需要在 Spring 容器中配置为 Bean:
Office 仅有一个属性:
清单 1. Office.java
package com.baobaotao;
public class Office {
private String officeNo =”001”;

//省略 get/setter

@Override
public String toString() {
return "officeNo:" + officeNo;
}
}
Car 拥有两个属性:
清单 2. Car.java
package com.baobaotao;

public class Car {
private String brand;
private double price;

// 省略 get/setter

@Override
public String toString() {
return "brand:" + brand + "," + "price:" + price;
}
}
Boss 拥有 Office 和 Car 类型的两个属性:
清单 3. Boss.java
package com.baobaotao;

public class Boss {
private Car car;
private Office office;

// 省略 get/setter

@Override
public String toString() {
return "car:" + car + "\n" + "office:" + office;
}
}
我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:
清单 4. beans.xml 将以上三个类配置成 Bean
<?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-2.5.xsd">
<bean id="boss" class="com.baobaotao.Boss">
<property name="car" ref="car"/>
<property name="office" ref="office" />
</bean>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="002"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
当我们运行以下代码时,控制台将正确打出 boss 的信息:
清单 5. 测试类:AnnoIoCTest.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnoIoCTest {

public static void main(String[] args) {
String[] locations = {"beans.xml"};
ApplicationContext ctx =
new ClassPathXmlApplicationContext(locations);
Boss boss = (Boss) ctx.getBean("boss");
System.out.println(boss);
}
}
这说明 Spring 容器已经正确完成了 Bean 创建和装配的工作。
回页首
使用 @Autowired 注释
Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。来看一下使用 @Autowired 进行成员变量自动注入的代码:
清单 6. 使用 @Autowired 注释的 Boss.java
package com.baobaotao;
import org.springframework.beans.factory.annotation.Autowired;

public class Boss {

@Autowired
private Car car;

@Autowired
private Office office;


}
Spring 通过一个 BeanPostProcessor 对 @Autowired 进行解析,所以要让 @Autowired 起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。
清单 7. 让 @Autowired 注释工作起来
<?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-2.5.xsd">

<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>

<!-- 移除 boss Bean 的属性注入配置的信息 -->
<bean id="boss" class="com.baobaotao.Boss"/>

<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
这样,当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。
按照上面的配置,Spring 将直接采用 Java 反射机制对 Boss 中的 car 和 office 这两个私有成员变量进行自动注入。所以对成员变量使用 @Autowired 后,您大可将它们的 setter 方法(setCar() 和 setOffice())从 Boss 中删除。
当然,您也可以通过 @Autowired 对方法或构造函数进行标注,来看下面的代码:
清单 8. 将 @Autowired 注释标注在 Setter 方法上
package com.baobaotao;

public class Boss {
private Car car;
private Office office;

@Autowired
public void setCar(Car car) {
this.car = car;
}

@Autowired
public void setOffice(Office office) {
this.office = office;
}

}
这时,@Autowired 将查找被标注的方法的入参类型的 Bean,并调用方法自动注入这些 Bean。而下面的使用方法则对构造函数进行标注:
清单 9. 将 @Autowired 注释标注在构造函数上
package com.baobaotao;

public class Boss {
private Car car;
private Office office;

@Autowired
public Boss(Car car ,Office office){
this.car = car;
this.office = office ;
}


}
由于 Boss() 构造函数有两个入参,分别是 car 和 office,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 Boss(Car car ,Office office) 的入参来创建 Boss Bean。
回页首
当候选 Bean 数目不为 1 时的应对方法
在默认情况下使用 @Autowired 注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean。我们可以来做一个实验:
清单 10. 候选 Bean 数目为 0 时
<?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-2.5.xsd ">

<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>

<bean id="boss" class="com.baobaotao.Boss"/>

<!-- 将 office Bean 注释掉 -->
<!-- <bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>-->

<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
由于 office Bean 被注释掉了,所以 Spring 容器中将没有类型为 Office 的 Bean 了,而 Boss 的 office 属性标注了 @Autowired,当启动 Spring 容器时,异常就产生了。
当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错。来看一下具体的例子:
清单 11. 使用 @Autowired(required = false)
package com.baobaotao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

public class Boss {

private Car car;
private Office office;

@Autowired
public void setCar(Car car) {
this.car = car;
}
@Autowired(required = false)
public void setOffice(Office office) {
this.office = office;
}

}
当然,一般情况下,使用 @Autowired 的地方都是需要注入 Bean 的,使用了自动注入而又允许不注入的情况一般仅会在开发期或测试期碰到(如为了快速启动 Spring 容器,仅引入一些模块的 Spring 配置文件),所以 @Autowired(required = false) 会很少用到。
和找不到一个类型匹配 Bean 相反的一个错误是:如果 Spring 容器中拥有多个候选 Bean,Spring 容器在启动时也会抛出 BeanCreationException 异常。来看下面的例子:
清单 12. 在 beans.xml 中配置两个 Office 类型的 Bean

<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="office2" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>

我们在 Spring 容器中配置了两个类型为 Office 类型的 Bean,当对 Boss 的 office 成员变量进行自动注入时,Spring 容器将无法确定到底要用哪一个 Bean,因此异常发生了。
Spring 允许我们通过 @Qualifier 注释指定注入 Bean 的名称,这样歧义就消除了,可以通过下面的方法解决异常:
清单 13. 使用 @Qualifier 注释指定注入 Bean 的名称
@Autowired
public void setOffice(@Qualifier("office")Office office) {
this.office = office;
}
@Qualifier("office") 中的 office 是 Bean 的名称,所以 @Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。@Autowired 可以对成员变量、方法以及构造函数进行注释,而 @Qualifier 的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同,所以 Spring 不将 @Autowired 和 @Qualifier 统一成一个注释类。下面是对成员变量和构造函数入参进行注释的代码:
对成员变量进行注释:
清单 14. 对成员变量使用 @Qualifier 注释
public class Boss {
@Autowired
private Car car;

@Autowired
@Qualifier("office")
private Office office;

}
对构造函数入参进行注释:
清单 15. 对构造函数变量使用 @Qualifier 注释
public class Boss {
private Car car;
private Office office;

@Autowired
public Boss(Car car , @Qualifier("office")Office office){
this.car = car;
this.office = office ;
}
}
@Qualifier 只能和 @Autowired 结合使用,是对 @Autowired 有益的补充。一般来讲,@Qualifier 对方法签名中入参进行注释会降低代码的可读性,而对成员变量注释则相对好一些。
回页首
使用 JSR-250 的注释
Spring 不但支持自己定义的 @Autowired 的注释,还支持几个由 JSR-250 规范定义的注释,它们分别是 @Resource、@PostConstruct 以及 @PreDestroy。
@Resource
@Resource 的作用相当于 @Autowired,只不过 @Autowired 按 byType 自动注入,面 @Resource 默认按 byName 自动注入罢了。@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将 @Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。
Resource 注释类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中,因此在使用之前必须将其加入到项目的类库中。来看一个使用 @Resource 的例子:
清单 16. 使用 @Resource 注释的 Boss.java
package com.baobaotao;

import javax.annotation.Resource;

public class Boss {
// 自动注入类型为 Car 的 Bean
@Resource
private Car car;

// 自动注入 bean 名称为 office 的 Bean
@Resource(name = "office")
private Office office;
}
一般情况下,我们无需使用类似于 @Resource(type=Car.class) 的注释方式,因为 Bean 的类型信息可以通过 Java 反射从代码中获取。
要让 JSR-250 的注释生效,除了在 Bean 类中标注这些注释外,还需要在 Spring 容器中注册一个负责处理这些注释的 BeanPostProcessor:
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
CommonAnnotationBeanPostProcessor 实现了 BeanPostProcessor 接口,它负责扫描使用了 JSR-250 注释的 Bean,并对它们进行相应的操作。
@PostConstruct 和 @PreDestroy
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法。关于 Spring 的生命周期,笔者在《精通 Spring 2.x—企业应用开发精解》第 3 章进行了详细的描述,有兴趣的读者可以查阅。
JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。
清单 17. 使用 @PostConstruct 和 @PreDestroy 注释的 Boss.java
package com.baobaotao;

import javax.annotation.Resource;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Boss {
@Resource
private Car car;

@Resource(name = "office")
private Office office;

@PostConstruct
public void postConstruct1(){
System.out.println("postConstruct1");
}

@PreDestroy
public void preDestroy1(){
System.out.println("preDestroy1");
}

}
您只需要在方法前标注 @PostConstruct 或 @PreDestroy,这些方法就会在 Bean 初始化后或销毁之前被 Spring 容器执行了。
我们知道,不管是通过实现 InitializingBean/DisposableBean 接口,还是通过 <bean> 元素的 init-method/destroy-method 属性进行配置,都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用 @PostConstruct 和 @PreDestroy 注释却可以指定多个初始化 / 销毁方法,那些被标注 @PostConstruct 或 @PreDestroy 注释的方法都会在初始化 / 销毁时被执行。
通过以下的测试代码,您将可以看到 Bean 的初始化 / 销毁方法是如何被执行的:
清单 18. 测试类代码
package com.baobaotao;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnoIoCTest {

public static void main(String[] args) {
String[] locations = {"beans.xml"};
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(locations);
Boss boss = (Boss) ctx.getBean("boss");
System.out.println(boss);
ctx.destroy();// 关闭 Spring 容器,以触发 Bean 销毁方法的执行
}
}
这时,您将看到标注了 @PostConstruct 的 postConstruct1() 方法将在 Spring 容器启动时,创建 Boss Bean 的时候被触发执行,而标注了 @PreDestroy 注释的 preDestroy1() 方法将在 Spring 容器关闭前销毁 Boss Bean 的时候被触发执行。
回页首
使用 <context:annotation-config/> 简化配置
Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。
而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 BeanPostProcessor 的方式,这就是 <context:annotation-config/>。请看下面的配置:
清单 19. 调整 beans.xml 配置文件
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>

<bean id="boss" class="com.baobaotao.Boss"/>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
<context:annotationconfig/> 将隐式地向 Spring 容器注册 AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及 equiredAnnotationBeanPostProcessor 这 4 个 BeanPostProcessor。
在配置文件中使用 context 命名空间之前,必须在 <beans> 元素中声明 context 命名空间。
回页首
使用 @Component
虽然我们可以通过 @Autowired 或 @Resource 在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 <bean> 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过 @Autowired 或 @Resource 为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的 @Component 注释就可以达到这个目标了。
下面,我们完全使用注释定义 Bean 并完成 Bean 之间装配:
清单 20. 使用 @Component 注释的 Car.java
package com.baobaotao;

import org.springframework.stereotype.Component;

@Component
public class Car {

}
仅需要在类定义处,使用 @Component 注释就可以将一个类定义了 Spring 容器中的 Bean。下面的代码将 Office 定义为一个 Bean:
清单 21. 使用 @Component 注释的 Office.java
package com.baobaotao;

import org.springframework.stereotype.Component;

@Component
public class Office {
private String officeNo = "001";

}
这样,我们就可以在 Boss 类中通过 @Autowired 注入前面定义的 Car 和 Office Bean 了。
清单 22. 使用 @Component 注释的 Boss.java
package com.baobaotao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("boss")
public class Boss {
@Autowired
private Car car;

@Autowired
private Office office;

}
@Component 有一个可选的入参,用于指定 Bean 的名称,在 Boss 中,我们就将 Bean 名称定义为“boss”。一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。
在使用 @Component 注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:
清单 23. 简化版的 beans.xml
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.baobaotao"/>
</beans>
这里,所有通过 <bean> 元素定义 Bean 的配置内容已经被移除,仅需要添加一行 <context:component-scan/> 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan/> 的 base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
<context:component-scan/> 还允许定义过滤器将基包下的某些类纳入或排除。Spring 支持以下 4 种类型的过滤方式,通过下表说明:
表 1. 扫描过滤方式
过滤器类型 说明
注释 假如 com.baobaotao.SomeAnnotation 是一个注释类,我们可以将使用该注释的类过滤出来。
类名指定 通过全限定类名进行过滤,如您可以指定将 com.baobaotao.Boss 纳入扫描,而将 com.baobaotao.Car 排除在外。
正则表达式 通过正则表达式定义过滤的类,如下所示: com\.baobaotao\.Default.*
AspectJ 表达式 通过 AspectJ 表达式定义过滤的类,如下所示: com. baobaotao..*Service+
下面是一个简单的例子:
<context:component-scan base-package="com.baobaotao">
<context:include-filter type="regex"
expression="com\.baobaotao\.service\..*"/>
<context:exclude-filter type="aspectj"
expression="com.baobaotao.util..*"/>
</context:component-scan>
值得注意的是 <context:component-scan/> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。
默认情况下通过 @Component 定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的 Bean,可以通过 @Scope 注释来达到目标,如以下代码所示:
清单 24. 通过 @Scope 指定 Bean 的作用范围
package com.baobaotao;
import org.springframework.context.annotation.Scope;

@Scope("prototype")
@Component("boss")
public class Boss {

}
这样,当从 Spring 容器中获取 boss Bean 时,每次返回的都是新的实例了。
回页首
采用具有特殊语义的注释
Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释,而用 @Component 对那些比较中立的类进行注释。
回页首
注释配置和 XML 配置的适用场合
是否有了这些 IOC 注释,我们就可以完全摒除原来 XML 配置的方式呢?答案是否定的。有以下几点原因:
注释配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的,(如 Service 使用了哪几个 DAO 类),这种配置信息不会在部署时发生调整,那么注释配置优于 XML 配置;反之如果这种依赖关系会在部署时发生调整,XML 配置显然又优于注释配置,因为注释是对 Java 源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
如果 Bean 不是自己编写的类(如 JdbcTemplate、SessionFactoryBean 等),注释配置将无法实施,此时 XML 配置是唯一可用的方式。
注释配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于 @Transaction 事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。
所以在实现应用中,我们往往需要同时使用注释配置和 XML 配置,对于类级别且不会发生变动的配置可以优先考虑注释配置;而对于那些第三方类以及容易发生调整的配置则应优先考虑使用 XML 配置。Spring 会在具体实施 Bean 创建和 Bean 注入之前将这两种配置方式的元信息融合在一起。

 

写道
概述
继 Spring 2.0 对 Spring MVC 进行重大升级后,Spring 2.5 又为 Spring MVC 引入了注解驱动功能。现在你无须让 Controller 继承任何接口,无需在 XML 配置文件中定义请求和 Controller 的映射关系,仅仅使用注解就可以让一个 POJO 具有 Controller 的绝大部分功能 —— Spring MVC 框架的易用性得到了进一步的增强.在框架灵活性、易用性和扩展性上,Spring MVC 已经全面超越了其它的 MVC 框架,伴随着 Spring 一路高唱猛进,可以预见 Spring MVC 在 MVC 市场上的吸引力将越来越不可抗拒。
本文将介绍 Spring 2.5 新增的 Sping MVC 注解功能,讲述如何使用注解配置替换传统的基于 XML 的 Spring MVC 配置。
回页首
一个简单的基于注解的 Controller
使用过低版本 Spring MVC 的读者都知道:当创建一个 Controller 时,我们需要直接或间接地实现 org.springframework.web.servlet.mvc.Controller 接口。一般情况下,我们是通过继承 SimpleFormController 或 MultiActionController 来定义自己的 Controller 的。在定义 Controller 后,一个重要的事件是在 Spring MVC 的配置文件中通过 HandlerMapping 定义请求和控制器的映射关系,以便将两者关联起来。
来看一下基于注解的 Controller 是如何定义做到这一点的,下面是使用注解的 BbtForumController:
清单 1. BbtForumController.java
package com.baobaotao.web;

import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

@Controller //<——①
@RequestMapping("/forum.do")
public class BbtForumController {

@Autowired
private BbtForumService bbtForumService;

@RequestMapping //<——②
public String listAllBoard() {
bbtForumService.getAllBoard();
System.out.println("call listAllBoard method.");
return "listBoard";
}
}
从上面代码中,我们可以看出 BbtForumController 和一般的类并没有区别,它没有实现任何特殊的接口,因而是一个地道的 POJO。让这个 POJO 与众不同的魔棒就是 Spring MVC 的注解!
在 ① 处使用了两个注解,分别是 @Controller 和 @RequestMapping。在“使用 Spring 2.5 基于注解驱动的 IoC”这篇文章里,笔者曾经指出过 @Controller、@Service 以及 @Repository 和 @Component 注解的作用是等价的:将一个类成为 Spring 容器的 Bean。由于 Spring MVC 的 Controller 必须事先是一个 Bean,所以 @Controller 注解是不可缺少的。
真正让 BbtForumController 具备 Spring MVC Controller 功能的是 @RequestMapping 这个注解。@RequestMapping 可以标注在类定义处,将 Controller 和特定请求关联起来;还可以标注在方法签名处,以便进一步对请求进行分流。在 ① 处,我们让 BbtForumController 关联“/forum.do”的请求,而 ② 处,我们具体地指定 listAllBoard() 方法来处理请求。所以在类声明处标注的 @RequestMapping 相当于让 POJO 实现了 Controller 接口,而在方法定义处的 @RequestMapping 相当于让 POJO 扩展 Spring 预定义的 Controller(如 SimpleFormController 等)。
为了让基于注解的 Spring MVC 真正工作起来,需要在 Spring MVC 对应的 xxx-servlet.xml 配置文件中做一些手脚。在此之前,还是先来看一下 web.xml 的配置吧:
清单 2. web.xml:启用 Spring 容器和 Spring MVC 框架
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>Spring Annotation MVC Sample</display-name>
<!-- Spring 服务层的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- Spring 容器启动监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<!-- Spring MVC 的Servlet,它将加载WEB-INF/annomvc-servlet.xml 的
配置文件,以启动Spring MVC模块-->
<servlet>
<servlet-name>annomvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>annomvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
web.xml 中定义了一个名为 annomvc 的 Spring MVC 模块,按照 Spring MVC 的契约,需要在 WEB-INF/annomvc-servlet.xml 配置文件中定义 Spring MVC 模块的具体配置。annomvc-servlet.xml 的配置内容如下所示:
清单 3. annomvc-servlet.xml
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.baobaotao.web"/>

<!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.
AnnotationMethodHandlerAdapter"/>

<!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
</beans>
因为 Spring 所有功能都在 Bean 的基础上演化而来,所以必须事先将 Controller 变成 Bean,这是通过在类中标注 @Controller 并在 annomvc-servlet.xml 中启用组件扫描机制来完成的,如 ① 所示。
在 ② 处,配置了一个 AnnotationMethodHandlerAdapter,它负责根据 Bean 中的 Spring MVC 注解对 Bean 进行加工处理,使这些 Bean 变成控制器并映射特定的 URL 请求。
而 ③ 处的工作是定义模型视图名称的解析规则,这里我们使用了 Spring 2.5 的特殊命名空间,即 p 命名空间,它将原先需要通过 <property> 元素配置的内容转化为 <bean> 属性配置,在一定程度上简化了 <bean> 的配置。
启动 Tomcat,发送 http://localhost/forum.do URL 请求,BbtForumController 的 listAllBoard() 方法将响应这个请求,并转向 WEB-INF/jsp/listBoard.jsp 的视图页面。
回页首
让一个 Controller 处理多个 URL 请求
在低版本的 Spring MVC 中,我们可以通过继承 MultiActionController 让一个 Controller 处理多个 URL 请求。使用 @RequestMapping 注解后,这个功能更加容易实现了。请看下面的代码:
清单 3. 每个请求处理参数对应一个 URL
package com.baobaotao.web;

import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BbtForumController {
@Autowired
private BbtForumService bbtForumService;

@RequestMapping("/listAllBoard.do") // <—— ①
public String listAllBoard() {
bbtForumService.getAllBoard();
System.out.println("call listAllBoard method.");
return "listBoard";
}

@RequestMapping("/listBoardTopic.do") // <—— ②
public String listBoardTopic(int topicId) {
bbtForumService.getBoardTopics(topicId);
System.out.println("call listBoardTopic method.");
return "listTopic";
}
}
在这里,我们分别在 ① 和 ② 处为 listAllBoard() 和 listBoardTopic() 方法标注了 @RequestMapping 注解,分别指定这两个方法处理的 URL 请求,这相当于将 BbtForumController 改造为 MultiActionController。这样 /listAllBoard.do 的 URL 请求将由 listAllBoard() 负责处理,而 /listBoardTopic.do?topicId=1 的 URL 请求则由 listBoardTopic() 方法处理。
对于处理多个 URL 请求的 Controller 来说,我们倾向于通过一个 URL 参数指定 Controller 处理方法的名称(如 method=listAllBoard),而非直接通过不同的 URL 指定 Controller 的处理方法。使用 @RequestMapping 注解很容易实现这个常用的需求。来看下面的代码:
清单 4. 一个 Controller 对应一个 URL,由请求参数决定请求处理方法
package com.baobaotao.web;

import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/bbtForum.do") // <—— ① 指定控制器对应URL请求
public class BbtForumController {

@Autowired
private BbtForumService bbtForumService;

// <—— ② 如果URL请求中包括"method=listAllBoard"的参数,由本方法进行处理
@RequestMapping(params = "method=listAllBoard")
public String listAllBoard() {
bbtForumService.getAllBoard();
System.out.println("call listAllBoard method.");
return "listBoard";
}

// <—— ③ 如果URL请求中包括"method=listBoardTopic"的参数,由本方法进行处理
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId) {
bbtForumService.getBoardTopics(topicId);
System.out.println("call listBoardTopic method.");
return "listTopic";
}
}
在类定义处标注的 @RequestMapping 让 BbtForumController 处理所有包含 /bbtForum.do 的 URL 请求,而 BbtForumController 中的请求处理方法对 URL 请求的分流规则在 ② 和 ③ 处定义分流规则按照 URL 的 method 请求参数确定。所以分别在类定义处和方法定义处使用 @RequestMapping 注解,就可以很容易通过 URL 参数指定 Controller 的处理方法了。
@RequestMapping 注解中除了 params 属性外,还有一个常用的属性是 method,它可以让 Controller 方法处理特定 HTTP 请求方式的请求,如让一个方法处理 HTTP GET 请求,而另一个方法处理 HTTP POST 请求,如下所示:
清单 4. 让请求处理方法处理特定的 HTTP 请求方法
package com.baobaotao.web;

import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/bbtForum.do")
public class BbtForumController {

@RequestMapping(params = "method=createTopic",method = RequestMethod.POST)
public String createTopic(){
System.out.println("call createTopic method.");
return "createTopic";
}
}
这样只有当 /bbtForum.do?method=createTopic 请求以 HTTP POST 方式提交时,createTopic() 方法才会进行处理。
回页首
处理方法入参如何绑定 URL 参数
按契约绑定
Controller 的方法标注了 @RequestMapping 注解后,它就能处理特定的 URL 请求。我们不禁要问:请求处理方法入参是如何绑定 URL 参数的呢?在回答这个问题之前先来看下面的代码:
清单 5. 按参数名匹配进行绑定
@RequestMapping(params = "method=listBoardTopic")
//<—— ① topicId入参是如何绑定URL请求参数的?
public String listBoardTopic(int topicId) {
bbtForumService.getBoardTopics(topicId);
System.out.println("call listBoardTopic method.");
return "listTopic";
}
当我们发送 http://localhost//bbtForum.do?method=listBoardTopic&topicId=10 的 URL 请求时,Spring 不但让 listBoardTopic() 方法处理这个请求,而且还将 topicId 请求参数在类型转换后绑定到 listBoardTopic() 方法的 topicId 入参上。而 listBoardTopic() 方法的返回类型是 String,它将被解析为逻辑视图的名称。也就是说 Spring 在如何给处理方法入参自动赋值以及如何将处理方法返回值转化为 ModelAndView 中的过程中存在一套潜在的规则,不熟悉这个规则就不可能很好地开发基于注解的请求处理方法,因此了解这个潜在规则无疑成为理解 Spring MVC 框架基于注解功能的核心问题。
我们不妨从最常见的开始说起:请求处理方法入参的类型可以是 Java 基本数据类型或 String 类型,这时方法入参按参数名匹配的原则绑定到 URL 请求参数,同时还自动完成 String 类型的 URL 请求参数到请求处理方法参数类型的转换。下面给出几个例子:
listBoardTopic(int topicId):和 topicId URL 请求参数绑定;
listBoardTopic(int topicId,String boardName):分别和 topicId、boardName URL 请求参数绑定;

特别的,如果入参是基本数据类型(如 int、long、float 等),URL 请求参数中一定要有对应的参数,否则将抛出 TypeMismatchException 异常,提示无法将 null 转换为基本数据类型。
另外,请求处理方法的入参也可以一个 JavaBean,如下面的 User 对象就可以作为一个入参:
清单 6. User.java:一个 JavaBean
package com.baobaotao.web;

public class User {
private int userId;
private String userName;
//省略get/setter方法
public String toString(){
return this.userName +","+this.userId;
}
}
下面是将 User 作为 listBoardTopic() 请求处理方法的入参:
清单 7. 使用 JavaBean 作为请求处理方法的入参
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId,User user) {
bbtForumService.getBoardTopics(topicId);
System.out.println("topicId:"+topicId);
System.out.println("user:"+user);
System.out.println("call listBoardTopic method.");
return "listTopic";
}
这时,如果我们使用以下的 URL 请求:http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom
topicId URL 参数将绑定到 topicId 入参上,而 userId 和 userName URL 参数将绑定到 user 对象的 userId 和 userName 属性中。和 URL 请求中不允许没有 topicId 参数不同,虽然 User 的 userId 属性的类型是基本数据类型,但如果 URL 中不存在 userId 参数,Spring 也不会报错,此时 user.userId 值为 0。如果 User 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptId URL 参数绑定。
通过注解指定绑定的 URL 参数
如果我们想改变这种默认的按名称匹配的策略,比如让 listBoardTopic(int topicId,User user) 中的 topicId 绑定到 id 这个 URL 参数,那么可以通过对入参使用 @RequestParam 注解来达到目的:
清单 8. 通过 @RequestParam 注解指定
package com.baobaotao.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;



@Controller
@RequestMapping("/bbtForum.do")
public class BbtForumController {

@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(@RequestParam("id") int topicId,User user) {
bbtForumService.getBoardTopics(topicId);
System.out.println("topicId:"+topicId);
System.out.println("user:"+user);
System.out.println("call listBoardTopic method.");
return "listTopic";
}

}
这里,对 listBoardTopic() 请求处理方法的 topicId 入参标注了 @RequestParam("id") 注解,所以它将和 id 的 URL 参数绑定。
绑定模型对象中某个属性
Spring 2.0 定义了一个 org.springframework.ui.ModelMap 类,它作为通用的模型数据承载对象,传递数据供视图所用。我们可以在请求处理方法中声明一个 ModelMap 类型的入参,Spring 会将本次请求模型对象引用通过该入参传递进来,这样就可以在请求处理方法内部访问模型对象了。来看下面的例子:
清单 9. 使用 ModelMap 访问请示对应的隐含模型对象
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(@RequestParam("id")int topicId,
User user,ModelMap model) {
bbtForumService.getBoardTopics(topicId);
System.out.println("topicId:" + topicId);
System.out.println("user:" + user);
//① 将user对象以currUser为键放入到model中
model.addAttribute("currUser",user);
return "listTopic";
}
对于当次请求所对应的模型对象来说,其所有属性都将存放到 request 的属性列表中。象上面的例子,ModelMap 中的 currUser 属性将放到 request 的属性列表中,所以可以在 JSP 视图页面中通过 request.getAttribute(“currUser”) 或者通过 ${currUser} EL 表达式访问模型对象中的 user 对象。从这个角度上看, ModelMap 相当于是一个向 request 属性列表中添加对象的一条管道,借由 ModelMap 对象的支持,我们可以在一个不依赖 Servlet API 的 Controller 中向 request 中添加属性。
在默认情况下,ModelMap 中的属性作用域是 request 级别是,也就是说,当本次请求结束后,ModelMap 中的属性将销毁。如果希望在多个请求中共享 ModelMap 中的属性,必须将其属性转存到 session 中,这样 ModelMap 的属性才可以被跨请求访问。
Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。请看下面的代码:
清单 10. 使模型对象的特定属性具有 Session 范围的作用域
package com.baobaotao.web;


import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/bbtForum.do")
@SessionAttributes("currUser") //①将ModelMap中属性名为currUser的属性
//放到Session属性列表中,以便这个属性可以跨请求访问
public class BbtForumController {

@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(@RequestParam("id")int topicId, User user,
ModelMap model) {
bbtForumService.getBoardTopics(topicId);
System.out.println("topicId:" + topicId);
System.out.println("user:" + user);
model.addAttribute("currUser",user); //②向ModelMap中添加一个属性
return "listTopic";
}

}
我们在 ② 处添加了一个 ModelMap 属性,其属性名为 currUser,而 ① 处通过 @SessionAttributes 注解将 ModelMap 中名为 currUser 的属性放置到 Session 中,所以我们不但可以在 listBoardTopic() 请求所对应的 JSP 视图页面中通过 request.getAttribute(“currUser”) 和 session.getAttribute(“currUser”) 获取 user 对象,还可以在下一个请求所对应的 JSP 视图页面中通过 session.getAttribute(“currUser”) 或 ModelMap#get(“currUser”) 访问到这个属性。
这里我们仅将一个 ModelMap 的属性放入 Session 中,其实 @SessionAttributes 允许指定多个属性。你可以通过字符串数组的方式指定多个属性,如 @SessionAttributes({“attr1”,”attr2”})。此外,@SessionAttributes 还可以通过属性类型指定要 session 化的 ModelMap 属性,如 @SessionAttributes(types = User.class),当然也可以指定多个类,如 @SessionAttributes(types = {User.class,Dept.class}),还可以联合使用属性名和属性类型指定:@SessionAttributes(types = {User.class,Dept.class},value={“attr1”,”attr2”})。
上面讲述了如何往ModelMap中放置属性以及如何使ModelMap中的属性拥有Session域的作用范围。除了在JSP视图页面中通过传统的方法访问ModelMap中的属性外,读者朋友可能会问:是否可以将ModelMap中的属性绑定到请求处理方法的入参中呢?答案是肯定的。Spring为此提供了一个@ModelAttribute的注解,下面是使用@ModelAttribute注解的例子:
清单 11. 使模型对象的特定属性具有 Session 范围的作用域
package com.baobaotao.web;

import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/bbtForum.do")
@SessionAttributes("currUser") //①让ModelMap的currUser属性拥有session级作用域
public class BbtForumController {

@Autowired
private BbtForumService bbtForumService;

@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(@RequestParam("id")int topicId, User user,
ModelMap model) {
bbtForumService.getBoardTopics(topicId);
System.out.println("topicId:" + topicId);
System.out.println("user:" + user);
model.addAttribute("currUser",user); //②向ModelMap中添加一个属性
return "listTopic";
}


@RequestMapping(params = "method=listAllBoard")
//③将ModelMap中的
public String listAllBoard(@ModelAttribute("currUser") User user) {
//currUser属性绑定到user入参中。
bbtForumService.getAllBoard();
System.out.println("user:"+user);
return "listBoard";
}
}
在 ② 处,我们向 ModelMap 中添加一个名为 currUser 的属性,而 ① 外的注解使这个 currUser 属性拥有了 session 级的作用域。所以,我们可以在 ③ 处通过 @ModelAttribute 注解将 ModelMap 中的 currUser 属性绑定以请求处理方法的 user 入参中。
所以当我们先调用以下 URL 请求: http://localhost/bbtForum.do?method=listBoardTopic&id=1&userName=tom&dept.deptId=12
以执行listBoardTopic()请求处理方法,然后再访问以下URL: http://localhost/sample/bbtForum.do?method=listAllBoard
你将可以看到 listAllBoard() 的 user 入参已经成功绑定到 listBoardTopic() 中注册的 session 级的 currUser 属性上了。
回页首
请求处理方法的签名规约
方法入参
我们知道标注了 @RequestMapping 注解的 Controller 方法就成为了请求处理方法,Spring MVC 允许极其灵活的请求处理方法签名方式。对于方法入参来说,它允许多种类型的入参,通过下表进行说明:
请求处理方法入参的可选类型 说明
Java 基本数据类型和 String 默认情况下将按名称匹配的方式绑定到 URL 参数上,可以通过 @RequestParam 注解改变默认的绑定规则
request/response/session 既可以是 Servlet API 的也可以是 Portlet API 对应的对象,Spring 会将它们绑定到 Servlet 和 Portlet 容器的相应对象上
org.springframework.web.context.request.WebRequest 内部包含了 request 对象
java.util.Locale 绑定到 request 对应的 Locale 对象上
java.io.InputStream/java.io.Reader 可以借此访问 request 的内容
java.io.OutputStream / java.io.Writer 可以借此操作 response 的内容
任何标注了 @RequestParam 注解的入参 被标注 @RequestParam 注解的入参将绑定到特定的 request 参数上。
java.util.Map / org.springframework.ui.ModelMap 它绑定 Spring MVC 框架中每个请求所创建的潜在的模型对象,它们可以被 Web 视图对象访问(如 JSP)
命令/表单对象(注:一般称绑定使用 HTTP GET 发送的 URL 参数的对象为命令对象,而称绑定使用 HTTP POST 发送的 URL 参数的对象为表单对象) 它们的属性将以名称匹配的规则绑定到 URL 参数上,同时完成类型的转换。而类型转换的规则可以通过 @InitBinder 注解或通过 HandlerAdapter 的配置进行调整
org.springframework.validation.Errors / org.springframework.validation.BindingResult 为属性列表中的命令/表单对象的校验结果,注意检验结果参数必须紧跟在命令/表单对象的后面
rg.springframework.web.bind.support.SessionStatus 可以通过该类型 status 对象显式结束表单的处理,这相当于触发 session 清除其中的通过 @SessionAttributes 定义的属性
Spring MVC 框架的易用之处在于,你可以按任意顺序定义请求处理方法的入参(除了 Errors 和 BindingResult 必须紧跟在命令对象/表单参数后面以外),Spring MVC 会根据反射机制自动将对应的对象通过入参传递给请求处理方法。这种机制让开发者完全可以不依赖 Servlet API 开发控制层的程序,当请求处理方法需要特定的对象时,仅仅需要在参数列表中声明入参即可,不需要考虑如何获取这些对象,Spring MVC 框架就象一个大管家一样“不辞辛苦”地为我们准备好了所需的一切。下面演示一下使用 SessionStatus 的例子:
清单 12. 使用 SessionStatus 控制 Session 级别的模型属性
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Owner owner,
BindingResult result, SessionStatus status) {//<——①
new OwnerValidator().validate(owner, result);
if (result.hasErrors()) {
return "ownerForm";
}
else {
this.clinic.storeOwner(owner);
status.setComplete();//<——②
return "redirect:owner.do?ownerId=" + owner.getId();
}
}
processSubmit() 方法中的 owner 表单对象将绑定到 ModelMap 的“owner”属性中,result 参数用于存放检验 owner 结果的对象,而 status 用于控制表单处理的状态。在 ② 处,我们通过调用 status.setComplete() 方法,该 Controller 所有放在 session 级别的模型属性数据将从 session 中清空。
方法返回参数
在低版本的 Spring MVC 中,请求处理方法的返回值类型都必须是 ModelAndView。而在 Spring 2.5 中,你拥有多种灵活的选择。通过下表进行说明:
请求处理方法入参的可选类型 说明
void
此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:
@RequestMapping("/welcome.do")
public void welcomeHandler() {
}
对应的逻辑视图名为“welcome”
String
此时逻辑视图名为返回的字符,如以下的方法:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return "ownerForm";
}
对应的逻辑视图名为“ownerForm”
org.springframework.ui.ModelMap
和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL,如下面的例子:
@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
对应的逻辑视图名为“vets”,返回的 ModelMap 将被作为请求对应的模型对象,可以在 JSP 视图页面中访问到。
ModelAndView 当然还可以是传统的 ModelAndView。
应该说使用 String 作为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求 URL 绑定,具有很大的灵活性,而模型数据又可以通过 ModelMap 控制。当然直接使用传统的 ModelAndView 也不失为一个好的选择。
回页首
注册自己的属性编辑器
Spring MVC 有一套常用的属性编辑器,这包括基本数据类型及其包裹类的属性编辑器、String 属性编辑器、JavaBean 的属性编辑器等。但有时我们还需要向 Spring MVC 框架注册一些自定义的属性编辑器,如特定时间格式的属性编辑器就是其中一例。
Spring MVC 允许向整个 Spring 框架注册属性编辑器,它们对所有 Controller 都有影响。当然 Spring MVC 也允许仅向某个 Controller 注册属性编辑器,对其它的 Controller 没有影响。前者可以通过 AnnotationMethodHandlerAdapter 的配置做到,而后者则可以通过 @InitBinder 注解实现。
下面先看向整个 Spring MVC 框架注册的自定义编辑器:
清单 13. 注册框架级的自定义属性编辑器
>bean class="org.springframework.web.servlet.mvc.annotation.
AnnotationMethodHandlerAdapter"<
>property name="webBindingInitializer"<
>bean class="com.baobaotao.web.MyBindingInitializer"/<
>/property<
>/bean<
MyBindingInitializer 实现了 WebBindingInitializer 接口,在接口方法中通过 binder 注册多个自定义的属性编辑器,其代码如下所示:
清单 14.自定义属性编辑器
package org.springframework.samples.petclinic.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.PetType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class MyBindingInitializer implements WebBindingInitializer {

public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class,
new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
}
}
如果希望某个属性编辑器仅作用于特定的 Controller,可以在 Controller 中定义一个标注 @InitBinder 注解的方法,可以在该方法中向 Controller 了注册若干个属性编辑器,来看下面的代码:
清单 15. 注册 Controller 级的自定义属性编辑器
@Controller
public class MyFormController {

@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

}
注意被标注 @InitBinder 注解的方法必须拥有一个 WebDataBinder 类型的入参,以便 Spring MVC 框架将注册属性编辑器的 WebDataBinder 对象传递进来。
回页首
如何准备数据
在编写 Controller 时,常常需要在真正进入请求处理方法前准备一些数据,以便请求处理或视图渲染时使用。在传统的 SimpleFormController 里,是通过复写其 referenceData() 方法来准备引用数据的。在 Spring 2.5 时,可以将任何一个拥有返回值的方法标注上 @ModelAttribute,使其返回值将会进入到模型对象的属性列表中。来看下面的例子:
清单 16. 定义为处理请求准备数据的方法
package com.baobaotao.web;

import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/bbtForum.do")
public class BbtForumController {

@Autowired
private BbtForumService bbtForumService;

@ModelAttribute("items")//<——①向模型对象中添加一个名为items的属性
public List<String> populateItems() {
List<String> lists = new ArrayList<String>();
lists.add("item1");
lists.add("item2");
return lists;
}

@RequestMapping(params = "method=listAllBoard")
public String listAllBoard(@ModelAttribute("currUser")User user, ModelMap model) {
bbtForumService.getAllBoard();
//<——②在此访问模型中的items属性
System.out.println("model.items:" + ((List<String>)model.get("items")).size());
return "listBoard";
}
}
在 ① 处,通过使用 @ModelAttribute 注解,populateItem() 方法将在任何请求处理方法执行前调用,Spring MVC 会将该方法返回值以“items”为名放入到隐含的模型对象属性列表中。
所以在 ② 处,我们就可以通过 ModelMap 入参访问到 items 属性,当执行 listAllBoard() 请求处理方法时,② 处将在控制台打印出“model.items:2”的信息。当然我们也可以在请求的视图中访问到模型对象中的 items 属性。
回页首
小结
Spring 2.5 对 Spring MVC 进行了很大增强,现在我们几乎完全可以使用基于注解的 Spring MVC 完全替换掉原来基于接口 Spring MVC 程序。基于注解的 Spring MVC 比之于基于接口的 Spring MVC 拥有以下几点好处:
方便请求和控制器的映射;
方便请求处理方法入参绑定URL参数;
Controller 不必继承任何接口,它仅是一个简单的 POJO。
但是基于注解的 Spring MVC 并不完美,还存在优化的空间,因为在某些配置上它比基于 XML 的配置更繁琐。比如对于处理多个请求的 Controller 来说,假设我们使用一个 URL 参数指定调用的处理方法(如 xxx.do?method=listBoardTopic),当使用注解时,每个请求处理方法都必须使用 @RequestMapping() 注解指定对应的 URL 参数(如 @RequestMapping(params = "method=listBoardTopic")),而在 XML 配置中我们仅需要配置一个 ParameterMethodNameResolver 就可以了。

 

写道
小结
Spring 在 2.1 以后对注释配置提供了强力的支持,注释配置功能成为 Spring 2.5 的最大的亮点之一。合理地使用 Spring 2.5 的注释配置,可以有效减少配置的工作量,提高程序的内聚性。但是这并不意味着传统 XML 配置将走向消亡,在第三方类 Bean 的配置,以及那些诸如数据源、缓存池、持久层操作模板类、事务管理等内容的配置上,XML 配置依然拥有不可替代的地位。

 

分享到:
评论

相关推荐

    使用Spring2.5的Autowired实现注释型的IOC

    java 使用Spring2.5的Autowired实现注释型的IOC

    使用 Spring 2_5 注释驱动的 IoC 功能.mht

    使用 Spring 2_5 注释驱动的 IoC 功能.mht 使用 Spring 2_5 注释驱动的 IoC 功能.mht

    spring2.5 api 离线版

    Spring2.5-Reference_zh_CN.chm Spring2.5-中文参考手册.chm spring——AOP,IOC.doc Spring框架快速入门之简介.doc spring配置全书.doc Spring中的IOC与AOP详解.ppt

    Spring2.5和Hibernate3集成--学习spring aop ioc

    Spring2.5和Hibernate3集成 采用声明式事务 1.声明式事务的配置 * 配置sessionFactory * 配置事务管理器 * 配置事务的传播特性 * 配置哪些类哪些方法使用事务 2.编写业务逻辑方法 * 继承...

    spring2.5 注解

    使用Spring2.5的Autowired实现注释型的IOC , 使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无需在xml文档里面添加bean的声明,大大减少了xml文档的维护

    Spring 2.5 jar 所有开发包及完整文档及项目开发实例

    13) spring-mock.jar需spring-core.jar,spring-beans.jar,spring-dao.jar,spring-context.jar,spring-jdbc.jarspring2.0和spring2.5及以上版本的jar包区别Spring 2.5的Jar打包 在Spring 2.5中, Spring Web MVC...

    spring 2.5 IOC 自动扫描,自动注入

    自己练习简单例子SPING 2.5类自动扫描,自动注入功能,加一些自己说明需要的可以下载.

    spring2.5.chm帮助文档(中文版)

    2. Spring 2.0和 2.5的新特性 2.1. 简介 2.2. 控制反转(IoC)容器 2.2.1. 新的bean作用域 2.2.2. 更简单的XML配置 2.2.3. 可扩展的XML编写 2.2.4. Annotation(注解)驱动配置 2.2.5. 在classpath中自动搜索组件...

    Spring2.5实例

    本实例是一个Spring与Hibernate结合的例子,很好地展示了用Spring的Ioc容器来灵活地定义Bean实现DAO和使用Spring的AOP实现事务管理。

    Spring通过注解实现IOC

    Spring通过注解实现IOC,Spring通过注解实现IOC,Spring通过注解实现IOC

    Spring2.5 IOC的简单实现

    NULL 博文链接:https://gddzmr.iteye.com/blog/694726

    使用Spring2.5TestContext测试框架

    本文内容包括: 概述直接使用JUnit测试Spring程序存在的不足一个需要测试的Spring...概述Spring2.5相比于Spring2.0所新增的最重要的功能可以归结为以下3点:基于注解的IoC功能;基于注解驱动的SpringMVC功能;基于注解

    springMVC详解以及注解说明 中文WORD版.rar

    基于注释(Annotation)的配置有越来越流行的趋势,Spring 2.5 顺应这种趋势,提供了完全基于注释配置 Bean、装配 Bean 的功能,您可以使用基于注释的 Spring IoC 替换原来基于 XML 的配置。本文通过实例详细讲述了 ...

    Spring的Aop和Ioc示例

    Spring的Aop和Ioc示例代码,代码通过了调试的,没得问题.对于初学者理解和使用Spring的Aop和Ioc是够了.

    Spring的IoC容器(《Spring揭秘》的精选版)

    针对Spring框架的主要功能以及开发者们遇到最多的问 题,首先介绍问题的相关背景,然后逐条进行深度剖析,最后通过分析来引入Spring框架可以提供的最佳解决方案。虽言Spring,却不局限于 Spring! 本书目录 目录 ...

    spring_iocspring_ioc

    spring_iocspring_iocspring_iocspring_iocspring_iocspring_iocspring_iocspring_iocspring_ioc

    Spring框架中的ioc的幽默解释

    Spring框架中的ioc的幽默解释

    spring2.5 学习笔记

    第三课:模拟Spring功能 5 第四课:搭建sping的运行环境 8 一、 建立一个新的项目 8 二、 建立spring的配置文件 8 三、 引入spring的jar包 8 四、 测试代码: 8 五、 注意接口的使用: 8 第五课:IOC(DI)配置及应用 ...

Global site tag (gtag.js) - Google Analytics