来源于http://www.blogjava.net/max/archive/2009/11/20/303112.html扩展Spring——使用Annotation将配置资源注入到Bean中
好久没有更新BLOG了,这几天经常有朋友留言或EMAIL关心或鼓励我。其实这篇文章我大约两星期前就写好了,本来想投稿IBM的developerWork中国。算啦,还是不等IBM的回复啦,发到我的自己的博客吧。
使用XML还是Annotation定义Bean
自从Spring2.5开始引入使用Annotation定义Bean的方式之后,业界时常会有一些关于“到底是应该使用XML还是Annotation定义Bean呢?”的讨论。笔者本人就比较中庸,喜欢两者结合使用——对于一些框架性的基础型的Bean使用XML,对于业务性的Bean则使用Annotation。
然而,什么是“框架性的基础型的Bean”呢?这些Bean可以理解为由第三方开源组件提供的基础Java类的、又或者开发者在其基础上扩展而来的Bean,如数据源org.apache.commons.dbcp.BasicDataSource、事务管理器org.springframework.orm.hibernate3.HibernateTransactionManager等。这些Bean一般在应用程序中数量较少,却起着框架性和全局性的作用,对于此类Bean使用XML的好处是必要时可以通过修改一个或几个XML文件即可改变应用程序行为满足实际的项目需求,如下清单1所示。
1<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
2destroy-method="close">
3<propertyname="driverClassName"value="${jdbc.driverClassName}"/>
4<propertyname="url"value="${jdbc.url}"/>
5<propertyname="username"value="${jdbc.username}"/>
6<propertyname="password"value="${jdbc.password}"/>
7</bean>
8<beanid="transactionManager"
9class="org.springframework.orm.hibernate3.HibernateTransactionManager">
10<propertyname="sessionFactory"ref="sessionFactory"/>
11</bean>
清单1.使用XML定义框架性的Bean
此外,我们再来解释一下什么是“业务性的Bean”。这些Bean相对比较容易理解,也就是开发者根据业务需求编写的XxxDao、XxxManager或XxxService等。它们的特点是为数众多,定义起来比较麻烦。Annotation方式的简洁性可以最大程度地减少这方便的繁锁,而且可以避免诸如打错类型名称等常见的小错误。对比清单2、3和4的代码大家应该会有更为深刻的理解。
1<beanid="myService"class="net.blogjava.max.service.MyServiceImpl">
2<propertyname="myDao1"ref="myDao1"/>
3<!--其它DAO引用-->
4<propertyname="myDaoN"ref="myDaoN"/>
5</bean>
清单2.使用XML定义业务性的Bean
1publicclassMyServiceImplimplementsMyService{
2privateMyDao1myDao1;
3//其它DAO
4privateMyDaoNmyDaoN;
5
6publicvoidsetMyDao1(MyDao1myDao1){
7this.myDao1=myDao1;
8}
9
10publicvoidsetMyDaoN(MyDaoNmyDaoN){
11this.myDaoN=myDaoN;
12}
13//其它业务代码
14}清单3.使用XML方式时Bean的代码
1@Service("myService")
2publicclassMyServiceImplimplementsMyService{
3@Resource
4privateMyDao1myDao1;
5//其它DAO
6@Resource
7privateMyDaoNmyDaoN;
8
9//其它业务代码
10}清单4.使用Annotation方式的Bean代码
清单2、3实现的功能与清单4一样,都是在Spring容器中定义一个MyServiceImpl类型的Bean。孰优孰劣?一目了然!
在Spring中配置应用程序
大家可以从清单1看到有${xxx.xxx}的写法,有Spring开发经验的朋友可能已经知道这是使用Spring框架时配置应用程序的方式之一。为了方便一些不甚了解的朋友,笔者在此也大概讲述一下这种配置方式的步骤。
首先,在工程中新建一个资源(Property)文件(笔者建议放在源代码目录下),通过“名称=取值”的方式定义应用的配置,如下清单5所示。
1jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
2jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:ORCL
3jdbc.username=max
4jdbc.password=secret清单5.配置代码片段
然后,定义一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类型的Bean,id可以为propertyConfigurer。通常我们需要通过设定它的locations属性指明应用程序配置文件的路径。例如,以下清单6的代码就是指明配置在构建路径(BuildPath)的根目录下的config.properties文件里。
1<beanid="propertyConfigurer"
2class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
3<propertyname="locations">
4<list>
5<value>classpath:config.properties</value>
6</list>
7</property>
8</bean>
清单6.Spring配置代码片段
最后,在XML中定义Bean时,使用${xxx}引用配置资源来初始化对象,如清单1所示。然而这种配置方式仅限于XML,如果我们需要在通过Annotation定义的业务性的Bean中使用配置资源呢?
实现通过Annotation向Bean注入配置资源
解决上述问题的思路很简单。首先,参考Spring注入Bean的Annotation(如@Resource等)编写一个类似的Annotation类,如下清单7所示。
1packagenet.blogjava.max.spring;
2
3importjava.lang.annotation.ElementType;
4importjava.lang.annotation.Retention;
5importjava.lang.annotation.RetentionPolicy;
6importjava.lang.annotation.Target;
7
8@Retention(RetentionPolicy.RUNTIME)
9@Target(ElementType.FIELD)
10public@interfaceConfig{
11Stringvalue()default"";
12}清单7.Config.java
上述Config类有只一个属性,所以用默认的“value”作为名称,而且此属性是可选的,换而言之,开发者可以通过@Config("配置名称")或简单地直接使用@Config来注入配置资源。当程序发现@Config的value为空时,会使用变量域(Field)的名称作为配置名称获取其值。
然后,通过上节配置的propertyConfigurer对象获取配置资源。不过通过阅读Spring的API文档或org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的源代码,笔者发现此对象并没有一个公共方法可以满足以上需求,但是它有一个受保护的方法,protectedvoidprocessProperties(ConfigurableListableBeanFactorybeanFactoryToProcess,Propertiesprops)throwsBeansException,作用是将从配置中读入的配置资源应用到Bean的生产工厂对象中。因此,我们可以继承此类,然后改写该方法,将参数props的引用放到类的全局变量里,接着通过它提供一个公共方法返回对应名称的配置资源,如下清单8所示。
1packagenet.blogjava.max.spring;
2
3importjava.util.Properties;
4
5importorg.springframework.beans.BeansException;
6importorg.springframework.beans.factory.config.ConfigurableListableBeanFactory;
7importorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
8
9publicclassExtendedPropertyPlaceholderConfigurerextends
10PropertyPlaceholderConfigurer{
11privatePropertiesprops;
12
13@Override
14protectedvoidprocessProperties(
15ConfigurableListableBeanFactorybeanFactory,Propertiesprops)
16throwsBeansException{
17super.processProperties(beanFactory,props);
18this.props=props;
19}
20
21publicObjectgetProperty(Stringkey){
22returnprops.get(key);
23}
24}清单8.ExtendedPropertyPlaceholderConfigurer.java
最后,我们需要通过实现Spring的某此生命周期回调方法,在Bean实例化之后将配置资源注入到标记有@Config的变量域(Field)中。通过阅读Spring的API文档,笔者发现org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor接口的方法booleanpostProcessAfterInstantiation(Objectbean,StringbeanName)throwsBeansException非常符合我们的需求,而且Spring的@Autowire就是通过实现此方法工作的。当然,在此大家已经可以着手编写该接口的实现类了。不过,由于该接口还不少其它方法,而这些方法跟我们的目标是毫无瓜葛的,直接实现它就不得不被迫编写一堆空的实现代码,所以笔者选择继承org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter虚基类,改写其postProcessAfterInstantiation方法。该虚基类是提供了一些接口(当然其中包括InstantiationAwareBeanPostProcessor)的空实现,因此开发者只需改写自己需要的方法即可,如下清单9所示。
1packagenet.blogjava.max.spring;
2
3importjava.lang.reflect.Field;
4importjava.lang.reflect.Modifier;
5
6importorg.springframework.beans.BeansException;
7importorg.springframework.beans.SimpleTypeConverter;
8importorg.springframework.beans.factory.annotation.Autowired;
9importorg.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
10importorg.springframework.stereotype.Component;
11importorg.springframework.util.ReflectionUtils;
12
13@Component//定义一个匿名Spring组件
14publicclassConfigAnnotationBeanPostProcessorextends
15InstantiationAwareBeanPostProcessorAdapter{
16@Autowired//自动注入ExtendedPropertyPlaceholderConfigurer对象,用于获取配置资源
17privateExtendedPropertyPlaceholderConfigurerpropertyConfigurer;
18
19//创建简单类型转换器
20privateSimpleTypeConvertertypeConverter=newSimpleTypeConverter();
21
22@Override
23publicbooleanpostProcessAfterInstantiation(finalObjectbean,StringbeanName)
24throwsBeansException{
25ReflectionUtils.doWithFields(bean.getClass(),newReflectionUtils.FieldCallback(){
26publicvoiddoWith(Fieldfield)throwsIllegalArgumentException,
27IllegalAccessException{
28Configcfg=field.getAnnotation(Config.class);
29if(cfg!=null){
30if(Modifier.isStatic(field.getModifiers())){
31thrownewIllegalStateException("@Configannotationisnotsupported
32onstaticfields");
33}
34
35//如果开发者没有设置@Config的value,则使用变量域的名称作为键查找配置资源
36Stringkey=cfg.value().length()<=0?field.getName():cfg.value();
37Objectvalue=propertyConfigurer.getProperty(key);
38
39if(value!=null){
40//转换配置值成其它非String类型
41Object_value=typeConverter.convertIfNecessary(value,field.getType());
42//使变量域可用,并且转换后的配置值注入其中
43ReflectionUtils.makeAccessible(field);
44field.set(bean,_value);
45}
46}
47}
48});
49
50//通常情况下返回true即可
51returntrue;
52}
53}清单9.ConfigAnnotationBeanPostProcessor.java
@Config使用示例
完成了上述步骤之后,下面我们用一个完整的例子来演示一下@Config的使用。首先,创建配置文件,如下清单10所示。
1demo.config1=DemoConfig\#1
2config2=314159清单10.src/config.properties
接着,编写Demo类,它将演示通过XML和Annotation的方式获取配置文件的资源。如下清单11所示。
1packagenet.blogjava.max.spring;
2
3importorg.springframework.context.ApplicationContext;
4importorg.springframework.context.support.ClassPathXmlApplicationContext;
5importorg.springframework.stereotype.Service;
6
7@Service("demoAnn")//通过Annotation的方式定义Bean
8publicclassDemo{
9@Config("demo.config1")//演示最常见的用法
10privateStringconfig1;
11
12@Config//演示通过域变量名字获取配置资源和数据类型转换
13privateIntegerconfig2;
14
15//演示通过XML方式注入配置资源
16privateStringconfig3;
17privateIntegerconfig4;
18
19publicvoidsetConfig3(Stringconfig3){
20this.config3=config3;
21}
22
23publicvoidsetConfig4(Integerconfig4){
24this.config4=config4;
25}
26
27publicvoidprintConfigAnn(){
28System.out.println("{config1="+config1+",config2="+config2
29+"}");
30}
31
32publicvoidprintConfigXML(){
33System.out.println("{config3="+config3+",config4="+config4
34+"}");
35}
36
37publicstaticvoidmain(String[]args){
38ApplicationContextappCtx=newClassPathXmlApplicationContext(
39"applicationContext.xml");
40
41DemodemoAnn=(Demo)appCtx.getBean("demoAnn");
42demoAnn.printConfigAnn();
43
44DemodemoXML=(Demo)appCtx.getBean("demoXML");
45demoXML.printConfigXML();
46}
47}清单11.Demo.java
由于本示例的目的是演示@Config的使用,所以采取了最简单编码风格,而并非大家使用Spring时常用的基于接口的编码风格。另外,本示例同时通过XML和Annotation的方式在Spring中定义Demo类型的Bean,前者通过类中的XML和两个Setter注入配置资源,后者则是通过Annotation和两个私有域变量。
最后,编写Spring的XML配置文件,如清单12所示。
1<?xmlversion="1.0"encoding="UTF-8"?>
2
3<beansxmlns=http://www.springframework.org/schema/beans
4xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
5xmlns:context=http://www.springframework.org/schema/context
6xsi:schemaLocation="http://www.springframework.org/schema/beans
7http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
8http://www.springframework.org/schema/context
9http://www.springframework.org/schema/context/spring-context-2.5.xsd">
10
11<!--指明需要进行Annotation扫描的包-->
12<context:component-scanbase-package="net.blogjava.max"/>
13
14<!--读入配置文件-->
15<beanid="propertyConfigurer"
16class="net.blogjava.max.spring.ExtendedPropertyPlaceholderConfigurer">
17<propertyname="locations">
18<list>
19<value>classpath:config.properties</value>
20</list>
21</property>
22</bean>
23
24<!--通过XML配置Demo的Bean,并注入配置资源-->
25<beanid="demoXML"class="net.blogjava.max.spring.Demo">
26<propertyname="config3"value="${demo.config1}"/>
27<propertyname="config4"value="${config2}"/>
28</bean>
29
30</beans>清单12.src/applicationContext.xml
完成了配置之后,大家可以运行Demo类的main方法,控制台会有如清单13的输出。这就证明了通过XML或Annotation可以注入相同配置资源,而且对比两者的代码,Annotation比XML更为简便和快捷。
1{config1=DemoConfig#1,config2=314159}
2{config3=DemoConfig#1,config4=314159}清单13.示例控制台输出
结束语
本文再三强调定义Bean时Annotation对比XML的优越性,尤其是针对业务性的对象;而配置又是每个应用程序必不可少的一部分,通过扩展Spring框架,开发者可以轻松地使用Annotation的方式实现应用程序配置。同时,笔者也希望Spring社区能够意识到这方面的需求,将其整合在以后发行的Spring版本之中。在此之前,大家可以通过文章后面的下载链接获得本文Eclipse工程的压缩包文件,运行示例或者将代码应用到您的工程之中。该代码不受任何版权保护,可以随便修改或发布。