您的位置:首页 > 编程语言 > Java开发

Spring注解详细介绍(四)

2011-09-27 13:33 477 查看
使用 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;

importorg.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 配置文件

<?xmlversion="1.0" encoding="UTF-8" ?>

<beansxmlns="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;

importorg.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;

importorg.springframework.beans.factory.annotation.Required;

importorg.springframework.beans.factory.annotation.Qualifier;

importorg.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

<?xmlversion="1.0" encoding="UTF-8" ?>

<beansxmlns="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-scanbase-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-scanbase-package="com.baobaotao">

<context:include-filtertype="regex"

expression="com\.baobaotao\.service\..*"/>

<context:exclude-filtertype="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;

importorg.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 对那些比较中立的类进行注释。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: