Spring2.5注释语法
Spring2.5注释语法
Spring的IoC
public?class?Foo?{①
??private?String?name;
??private?int?age;
??public?String?toString(){
?????return?"The?Foo's?Name?is?:?"?+?this.name?+?"?The?Foo's?Age?is?:?"?+?this.age;
??}
??public?String?getName()?{
}
??public?void?setName(String?name)?{
}
??public?int?getAge()?{
}
??public?void?setAge(int?age)?{
}
}
?
public?class?Bar?{②
??private?String?address;
??public?String?toString(){
?????return?"The?Bar's?Address?is?:?"?+?this.address;
??}
??public?String?getAddress()?{
}
??public?void?setAddress(String?address)?{
}
}
?
public?class?Base?{③
??private?Foo?foo;
??private?Bar?bar;
??public?String?toString(){
?????return?"Base?:?["?+?this.foo.toString()?+"?"+?this.bar.toString()+?"]";
??}
??public?Foo?getFoo()?{
}
??public?void?setFoo(Foo?foo)?{
}
??public?Bar?getBar()?{
}
??public?void?setBar(Bar?bar)?{
}
}
<?xml?version="1.0"?encoding="UTF-8"?>
<beans?xmlns="
">
??<bean?id="foo"?class="com.tony.test.Foo">
?????<property?name="name"?value="Tony"/>
?????<property?name="age"?value="27"/>
??</bean?>
??<bean?id="bar"?class="com.tony.test.Bar">
?????<property?name="address"?value="China?Tianjin"/>
??</bean>
??<bean?id="base"?class="com.tony.test.Base">
?????<property?name="foo">
????????<ref?local="foo"/>
?????</property>
?????<property?name="bar">
????????<ref?local="bar"/>
?????</property>
??</bean>
</beans>
?
import?org.springframework.context.ApplicationContext;
import?org.springframework.context.support.ClassPathXmlApplicationContext;
public?class?MainClass?{④
??public?static?void?main(String[]?args)?{????
????????String[]?locations?=?{"spring-config-beans.xml"};????
????????ApplicationContext?ctx?=?new?ClassPathXmlApplicationContext(locations);????
????????Base?main?=?(Base)?ctx.getBean("base");⑤???
????????System.out.println(main);⑥???
???}
}
我们来看看上面代码的含义,首先在代码①和②处我们分别定义了两个名为Foo和Bar的Bean,在③处我们通过set方法将两个Bean注入进Base类中,并且在Base类中定义了toString方法来打印出Foo和Bar的信息,在④处我们定义了一个MainClass来执行我们的代码,在⑤处我们通过getBean获得配置文件中配置的id为base的Bean并在⑥出将其信息打印至控制台,控制台输出信息如下:
Base : [The Foo's Name is : Tony The Foo's Age is : 27 The Bar's Address is : China Tianjin]
看到上面习以为常的配置信息和set get方法我们根本不会有任何想法,可是当我们看到了Spring2.5注释特性的时候我们发现自己真的错了,程序竟然还可以写成这么简单。
import?org.springframework.beans.factory.annotation.Autowired;
public?class?Base?{
??@Autowired① 使用了一个名为Autowired的注释
??private?Foo?foo;
??@Autowired②
??private?Bar?bar;
??public?String?toString(){
?????return?"Base?:?["?+?this.foo.toString()?+"?"+?this.bar.toString()+?"]";
??}
}
<!--?该?BeanPostProcessor?将自动对标注?@Autowired?的?Bean?进行注入?-->③??
??<bean?class="org.springframework.beans.factory.annotation.
??????????????????????????????AutowiredAnnotationBeanPostProcessor"/>
??
??<bean?id="foo"?class="com.tony.test.Foo">
?????<property?name="name"?value="Tony"/>
?????<property?name="age"?value="27"/>
??</bean>
??<bean?id="bar"?class="com.tony.test.Bar">
?????<property?name="address"?value="China?Tianjin"/>
??</bean>
??<!--?此时移除了Base的配置信息?-->?④
??<bean?id="base"?class="com.tony.test.Base"/>
我们在①和②处使用了@Autowired注释,它可以对类的成员变量、方法及构造函数进行标注,完成自动装配的工作,在③处我们为了使@Autowired注释生效必须在Spring容器中声明AutowiredAnnotationBeanPostProcessor Bean它通过扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其相匹配(默认按类型匹配)的 Bean,并将其注入,而此时我们在声明Base的时候(④处)就不用写它的配置信息了,更可以将Base类中的set和get方法删除。@Autowired还可以通过类的构造函数来进行自动装配。
在默认情况下使用 @Autowired 注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean
import?org.springframework.beans.factory.annotation.Autowired;
public?class?Base?{
??private?Foo?foo;
??private?Bar?bar;
??@Autowired
??public?Base(Foo?foo,Bar?bar){?①
?????this.foo?=?foo;
?????this.bar?=?bar;
??}
??public?String?toString(){
?????return?"Base?:?["?+?this.foo.toString()?+"?"+?this.bar.toString()+?"]";
??}
}
我们增加了一个构造函数,通过它来对我们的成员变量进行赋值,我们同时也为这个构造函数添加了@Autowired注释(①处)使其可以自动将Foo和Bar两个成员变量装配进来。
当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错
有时我们会遇到这样一种情况,我们定义了两个类型相同数据不同的Bean,我们此时需要用到其中一个Bean来供我们使用,使用@Qualifier注释就可以满足我们的要求,当使用@Qualifier注释时自动注入的策略就从 byType 转变成 byName 了。
<bean?id="bar"?class="com.tony.test.Bar">①
??<property?name="address"?value="China?Tianjin"/>
</bean>
<bean?id="bar2"?class="com.tony.test.Bar">②
??<property?name="address"?value="China?Beijing"/>
</bean>
?
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.beans.factory.annotation.Qualifier;
public?class?Base?{
??private?Bar?bar;
??@Autowired ③
??public?Base(@Qualifier("bar2")Bar?bar){ ④
?????this.bar?=?bar;
??}
??public?String?toString(){
?????return?"Base?:?["+?this.bar.toString()+?"]";
??}
}
①和②处我们分别定义了两个类型为Bar的Bean,②处Bar的address为China Beijing并且Bean的名称为bar2,在代码清单4.2的③处我们同样使用了@Autowired注释为Bar的构造函数进行自动装配,可是在④处我们通过@Qualifier("bar2")来明确指定我们需要将id为bar2的Bean装配进来。我们还可以为成员变量使用@Qualifier注释。
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.beans.factory.annotation.Qualifier;
public?class?Base?{
??@Autowired?①
??@Qualifier("bar2")?②
??private?Bar?bar;
??public?String?toString(){
?????return?"Base?:?["+?this.bar.toString()+?"]";
??}
}
使用了@Autowired注释后我们发现自动注入真的非常简单,但是我们还是得在配置文件中定义相应的<Bean>,如果我们能在配置文件中完全移除Bean的定义那就更好了,Spring2.5就为我们提供了这一可能。
import?org.springframework.stereotype.Component;
@Component?①
public?class?Bar?{
??private?String?address?=?"China?Tianjin";
??public?String?toString(){
?????return?"The?Bar's?Address?is?:?"?+?this.address;
??}
}
?
import?org.springframework.stereotype.Component;
@Component("base")?②
public?class?Base?{
??@Resource
??private?Bar?bar;
??public?String?toString(){
?????return?"Base?:?["+?this.bar.toString()+?"]";
??}
}
<?xml?version="1.0"?encoding="UTF-8"?>
<beans?xmlns="
">
??<context:component-scan?base-package="com.tony.test"/>?③
</beans>
我们使用了一个@Component注释(①处),使用@Component 注释就可以将一个类定义成为Spring 容器中的 Bean。在代码清单5.2的②处我们也同样使用了@Component注释,而此时我们使用了它提供的一个可选的入参将Bean的名称定义为base,最后在③处我们将以前定义Bean的内容全部移除,添加了一行<context:component-scan/>,其中的base-package属性指定了需要扫描的类包,它会自动递归下面的子包。
?
import?org.springframework.beans.factory.annotation.Autowired;?import?org.springframework.context.annotation.Scope;
import?org.springframework.stereotype.Component;
@Scope("prototype")?①
@Component("base")
public?class?Base?{
??@Autowired
??private?Bar?bar;
??public?String?toString(){
?????return?"Base?:?["+?this.bar.toString()+?"]";
??}
}
在代码清单6.1中的①处我们添加了一个@Scope注释,这样当我们从 Spring 容器中获取 base 时,每次返回的都是一个新的实例了。
?
@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 的例子:
?
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 是有生命周期的,
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");????????
????}???????
????…???????
}?????JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。
您只需要在方法前标注 @PostConstruct 或 @PreDestroy,这些方法就会在 Bean 初始化后或销毁之前被 Spring 容器执行了。
我们知道,不管是通过实现 InitializingBean/DisposableBean 接口,还是通过 <bean> 元素的 init-method/destroy-method 属性进行配置,都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用 @PostConstruct 和 @PreDestroy 注释却可以指定多个初始化 / 销毁方法,那些被标注 @PostConstruct 或 @PreDestroy 注释的方法都会在初始化 / 销毁时被执行。
七、使用 <context:annotation-config/> 简化配置
Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。
而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 BeanPostProcessor 的方式,这就是 <context:annotation-config/>。请看下面的配置:
<?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 命名空间。
Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释,而用 @Component 对那些比较中立的类进行注释。
在使用 @Component 注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:
<?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 种类型的过滤方式,通过下表说明:
过滤器类型 说明
注释 假如 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/> 移除了。
注释配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的,(如 Service 使用了哪几个 DAO 类),这种配置信息不会在部署时发生调整,那么注释配置优于 XML 配置;反之如果这种依赖关系会在部署时发生调整,XML 配置显然又优于注释配置,因为注释是对 Java 源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
如果 Bean 不是自己编写的类(如 JdbcTemplate、SessionFactoryBean 等),注释配置将无法实施,此时 XML 配置是唯一可用的方式。
注释配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于 @Transaction 事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。