`
peizhiinfo
  • 浏览: 1426881 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多
Java代码
使用Spring2.5的Autowired实现注释型的IOC
  1. 使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无需在xml文档里面添加bean的声明,大大减少了xml文档的维护。(偶喜欢这个功能,因为偶对xml不感冒)。以下是一个例子:
  2. 先编写接口Man:
  3. publicinterfaceMan{
  4. publicStringsayHello();
  5. }
  6. 然后写Man的实现类Chinese和American:
  7. @Service
  8. publicclassChineseimplementsMan{
  9. publicStringsayHello(){
  10. return"IamChinese!";
  11. }
  12. }
  13. @Service
  14. publicclassAmericanimplementsMan{
  15. publicStringsayHello(){
  16. return"IamAmerican!";
  17. }
  18. }
  19. @Service注释表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,例如Chinese实例化为chinese,American实例化为american,如果需要自己改名字则:@Service("你自己改的bean名")。
  20. beans.xml
  21. <?xmlversion="1.0"encoding="UTF-8"?>
  22. <beansxmlns="http://www.springframework.org/schema/beans"
  23. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  24. xmlns:context="http://www.springframework.org/schema/context"
  25. xsi:schemaLocation="http://www.springframework.org/schema/beans
  26. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  27. http://www.springframework.org/schema/context
  28. http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  29. <context:annotation-config/>
  30. <context:component-scanbase-package="testspring.main"/>
  31. </beans>
  32. 在spring的配置文件里面只需要加上<context:annotation-config/>和<context:component-scanbase-package="需要实现注入的类所在包"/>,可以使用base-package="*"表示全部的类。
  33. 编写主类测试:
  34. @Service
  35. publicclassMain{
  36. @Autowired
  37. @Qualifier("chinese")
  38. privateManman;
  39. publicstaticvoidmain(String[]args){
  40. //TODOcodeapplicationlogichere
  41. ApplicationContextctx=newClassPathXmlApplicationContext("beans.xml");
  42. Mainmain=(Main)ctx.getBean("main");
  43. System.out.println(main.getMan().sayHello());
  44. }
  45. publicMangetMan(){
  46. returnman;
  47. }
  48. }
  49. 在Man接口前面标上@Autowired@Qualifier注释使得Man接口可以被容器注入,当Man接口存在两个实现类的时候必须指定其中一个来注入,使用实现类首字母小写的字符串来注入。否则可以省略,只写@Autowired
  50. **********************
  51. 使用Spring2.5注释驱动的IoC功能
  52. 发表于08-03-0420:38|阅读1285|评分(暂无)
  53. 概述
  54. 注释配置相对于XML配置具有很多的优势:
  55. 它可以充分利用Java的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用JPA注释配置ORM映射时,我们就不需要指定PO的属性名、类型等信息,如果关系表字段和PO属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过Java反射机制获取。
  56. 注释和Java代码位于一个文件中,而XML配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和Java代码放在一起,有助于增强程序的内聚性。而采用独立的XML配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
  57. 因此在很多情况下,注释配置比XML配置更受欢迎,注释配置有进一步流行的趋势。Spring2.5的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分XML配置的功能。在这篇文章里,我们将向您讲述使用注释进行Bean定义和依赖注入的内容。
  58. 回页首
  59. 原来我们是怎么做的
  60. 在使用注释配置之前,先来回顾一下传统上是如何配置Bean并完成Bean之间依赖关系的建立。下面是3个类,它们分别是Office、Car和Boss,这3个类需要在Spring容器中配置为Bean:
  61. Office仅有一个属性:
  62. 清单1.Office.java
  63. packagecom.baobaotao;
  64. publicclassOffice{
  65. privateStringofficeNo=”001”;
  66. //省略get/setter
  67. @Override
  68. publicStringtoString(){
  69. return"officeNo:"+officeNo;
  70. }
  71. }
  72. Car拥有两个属性:
  73. 清单2.Car.java
  74. packagecom.baobaotao;
  75. publicclassCar{
  76. privateStringbrand;
  77. privatedoubleprice;
  78. //省略get/setter
  79. @Override
  80. publicStringtoString(){
  81. return"brand:"+brand+","+"price:"+price;
  82. }
  83. }
  84. Boss拥有Office和Car类型的两个属性:
  85. 清单3.Boss.java
  86. packagecom.baobaotao;
  87. publicclassBoss{
  88. privateCarcar;
  89. privateOfficeoffice;
  90. //省略get/setter
  91. @Override
  92. publicStringtoString(){
  93. return"car:"+car+"\n"+"office:"+office;
  94. }
  95. }
  96. 我们在Spring容器中将Office和Car声明为Bean,并注入到BossBean中:下面是使用传统XML完成这个工作的配置文件beans.xml:
  97. 清单4.beans.xml将以上三个类配置成Bean
  98. <?xmlversion="1.0"encoding="UTF-8"?>
  99. <beansxmlns="http://www.springframework.org/schema/beans"
  100. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  101. xsi:schemaLocation="http://www.springframework.org/schema/beans
  102. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  103. <beanid="boss"class="com.baobaotao.Boss">
  104. <propertyname="car"ref="car"/>
  105. <propertyname="office"ref="office"/>
  106. </bean>
  107. <beanid="office"class="com.baobaotao.Office">
  108. <propertyname="officeNo"value="002"/>
  109. </bean>
  110. <beanid="car"class="com.baobaotao.Car"scope="singleton">
  111. <propertyname="brand"value="红旗CA72"/>
  112. <propertyname="price"value="2000"/>
  113. </bean>
  114. </beans>
  115. 当我们运行以下代码时,控制台将正确打出boss的信息:
  116. 清单5.测试类:AnnoIoCTest.java
  117. importorg.springframework.context.ApplicationContext;
  118. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  119. publicclassAnnoIoCTest{
  120. publicstaticvoidmain(String[]args){
  121. String[]locations={"beans.xml"};
  122. ApplicationContextctx=
  123. newClassPathXmlApplicationContext(locations);
  124. Bossboss=(Boss)ctx.getBean("boss");
  125. System.out.println(boss);
  126. }
  127. }
  128. 这说明Spring容器已经正确完成了Bean创建和装配的工作。
  129. 回页首
  130. 使用@Autowired注释
  131. Spring2.5引入了@Autowired注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。来看一下使用@Autowired进行成员变量自动注入的代码:
  132. 清单6.使用@Autowired注释的Boss.java
  133. packagecom.baobaotao;
  134. importorg.springframework.beans.factory.annotation.Autowired;
  135. publicclassBoss{
  136. @Autowired
  137. privateCarcar;
  138. @Autowired
  139. privateOfficeoffice;
  140. }
  141. Spring通过一个BeanPostProcessor对@Autowired进行解析,所以要让@Autowired起作用必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessorBean。
  142. 清单7.让@Autowired注释工作起来
  143. <?xmlversion="1.0"encoding="UTF-8"?>
  144. <beansxmlns="http://www.springframework.org/schema/beans"
  145. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  146. xsi:schemaLocation="http://www.springframework.org/schema/beans
  147. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  148. <!--该BeanPostProcessor将自动起作用,对标注@Autowired的Bean进行自动注入-->
  149. <beanclass="org.springframework.beans.factory.annotation.
  150. AutowiredAnnotationBeanPostProcessor"/>
  151. <!--移除bossBean的属性注入配置的信息-->
  152. <beanid="boss"class="com.baobaotao.Boss"/>
  153. <beanid="office"class="com.baobaotao.Office">
  154. <propertyname="officeNo"value="001"/>
  155. </bean>
  156. <beanid="car"class="com.baobaotao.Car"scope="singleton">
  157. <propertyname="brand"value="红旗CA72"/>
  158. <propertyname="price"value="2000"/>
  159. </bean>
  160. </beans>
  161. 这样,当Spring容器启动时,AutowiredAnnotationBeanPostProcessor将扫描Spring容器中所有Bean,当发现Bean中拥有@Autowired注释时就找到和其匹配(默认按类型匹配)的Bean,并注入到对应的地方中去。
  162. 按照上面的配置,Spring将直接采用Java反射机制对Boss中的car和office这两个私有成员变量进行自动注入。所以对成员变量使用@Autowired后,您大可将它们的setter方法(setCar()和setOffice())从Boss中删除。
  163. 当然,您也可以通过@Autowired对方法或构造函数进行标注,来看下面的代码:
  164. 清单8.将@Autowired注释标注在Setter方法上
  165. packagecom.baobaotao;
  166. publicclassBoss{
  167. privateCarcar;
  168. privateOfficeoffice;
  169. @Autowired
  170. publicvoidsetCar(Carcar){
  171. this.car=car;
  172. }
  173. @Autowired
  174. publicvoidsetOffice(Officeoffice){
  175. this.office=office;
  176. }
  177. }
  178. 这时,@Autowired将查找被标注的方法的入参类型的Bean,并调用方法自动注入这些Bean。而下面的使用方法则对构造函数进行标注:
  179. 清单9.将@Autowired注释标注在构造函数上
  180. packagecom.baobaotao;
  181. publicclassBoss{
  182. privateCarcar;
  183. privateOfficeoffice;
  184. @Autowired
  185. publicBoss(Carcar,Officeoffice){
  186. this.car=car;
  187. this.office=office;
  188. }
  189. }
  190. 由于Boss()构造函数有两个入参,分别是car和office,@Autowired将分别寻找和它们类型匹配的Bean,将它们作为Boss(Carcar,Officeoffice)的入参来创建BossBean。
  191. 回页首
  192. 当候选Bean数目不为1时的应对方法
  193. 在默认情况下使用@Autowired注释进行自动注入时,Spring容器中匹配的候选Bean数目必须有且仅有一个。当找不到一个匹配的Bean时,Spring容器将抛出BeanCreationException异常,并指出必须至少拥有一个匹配的Bean。我们可以来做一个实验:
  194. 清单10.候选Bean数目为0
  195. <?xmlversion="1.0"encoding="UTF-8"?>
  196. <beansxmlns="http://www.springframework.org/schema/beans"
  197. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  198. xsi:schemaLocation="http://www.springframework.org/schema/beans
  199. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  200. <beanclass="org.springframework.beans.factory.annotation.
  201. AutowiredAnnotationBeanPostProcessor"/>
  202. <beanid="boss"class="com.baobaotao.Boss"/>
  203. <!--将officeBean注释掉-->
  204. <!--<beanid="office"class="com.baobaotao.Office">
  205. <propertyname="officeNo"value="001"/>
  206. </bean>-->
  207. <beanid="car"class="com.baobaotao.Car"scope="singleton">
  208. <propertyname="brand"value="红旗CA72"/>
  209. <propertyname="price"value="2000"/>
  210. </bean>
  211. </beans>
  212. 由于officeBean被注释掉了,所以Spring容器中将没有类型为Office的Bean了,而Boss的office属性标注了@Autowired,当启动Spring容器时,异常就产生了。
  213. 当不能确定Spring容器中一定拥有某个类的Bean时,可以在需要自动注入该类Bean的地方可以使用@Autowired(required=false),这等于告诉Spring:在找不到匹配Bean时也不报错。来看一下具体的例子:
  214. 清单11.使用@Autowired(required=false)
  215. packagecom.baobaotao;
  216. importorg.springframework.beans.factory.annotation.Autowired;
  217. importorg.springframework.beans.factory.annotation.Required;
  218. publicclassBoss{
  219. privateCarcar;
  220. privateOfficeoffice;
  221. @Autowired
  222. publicvoidsetCar(Carcar){
  223. this.car=car;
  224. }
  225. @Autowired(required=false)
  226. publicvoidsetOffice(Officeoffice){
  227. this.office=office;
  228. }
  229. }
  230. 当然,一般情况下,使用@Autowired的地方都是需要注入Bean的,使用了自动注入而又允许不注入的情况一般仅会在开发期或测试期碰到(如为了快速启动Spring容器,仅引入一些模块的Spring配置文件),所以@Autowired(required=false)会很少用到。
  231. 和找不到一个类型匹配Bean相反的一个错误是:如果Spring容器中拥有多个候选Bean,Spring容器在启动时也会抛出BeanCreationException异常。来看下面的例子:
  232. 清单12.在beans.xml中配置两个Office类型的Bean
  233. <beanid="office"class="com.baobaotao.Office">
  234. <propertyname="officeNo"value="001"/>
  235. </bean>
  236. <beanid="office2"class="com.baobaotao.Office">
  237. <propertyname="officeNo"value="001"/>
  238. </bean>
  239. 我们在Spring容器中配置了两个类型为Office类型的Bean,当对Boss的office成员变量进行自动注入时,Spring容器将无法确定到底要用哪一个Bean,因此异常发生了。
  240. Spring允许我们通过@Qualifier注释指定注入Bean的名称,这样歧义就消除了,可以通过下面的方法解决异常:
  241. 清单13.使用@Qualifier注释指定注入Bean的名称
  242. @Autowired
  243. publicvoidsetOffice(@Qualifier("office")Officeoffice){
  244. this.office=office;
  245. }
  246. @Qualifier("office")中的office是Bean的名称,所以@Autowired@Qualifier结合使用时,自动注入的策略就从byType转变成byName了。@Autowired可以对成员变量、方法以及构造函数进行注释,而@Qualifier的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同,所以Spring不将@Autowired@Qualifier统一成一个注释类。下面是对成员变量和构造函数入参进行注释的代码:
  247. 对成员变量进行注释:
  248. 清单14.对成员变量使用@Qualifier注释
  249. publicclassBoss{
  250. @Autowired
  251. privateCarcar;
  252. @Autowired
  253. @Qualifier("office")
  254. privateOfficeoffice;
  255. }
  256. 对构造函数入参进行注释:
  257. 清单15.对构造函数变量使用@Qualifier注释
  258. publicclassBoss{
  259. privateCarcar;
  260. privateOfficeoffice;
  261. @Autowired
  262. publicBoss(Carcar,@Qualifier("office")Officeoffice){
  263. this.car=car;
  264. this.office=office;
  265. }
  266. }
  267. @Qualifier只能和@Autowired结合使用,是对@Autowired有益的补充。一般来讲,@Qualifier对方法签名中入参进行注释会降低代码的可读性,而对成员变量注释则相对好一些。
  268. 回页首
  269. 使用JSR-250的注释
  270. Spring不但支持自己定义的@Autowired的注释,还支持几个由JSR-250规范定义的注释,它们分别是@Resource@PostConstruct以及@PreDestroy
  271. @Resource
  272. @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,面@Resource默认按byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,Spring将@Resource注释的name属性解析为Bean的名字,而type属性则解析为Bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
  273. Resource注释类位于Spring发布包的lib/j2ee/common-annotations.jar类包中,因此在使用之前必须将其加入到项目的类库中。来看一个使用@Resource的例子:
  274. 清单16.使用@Resource注释的Boss.java
  275. packagecom.baobaotao;
  276. importjavax.annotation.Resource;
  277. publicclassBoss{
  278. //自动注入类型为Car的Bean
  279. @Resource
  280. privateCarcar;
  281. //自动注入bean名称为office的Bean
  282. @Resource(name="office")
  283. privateOfficeoffice;
  284. }
  285. 一般情况下,我们无需使用类似于@Resource(type=Car.class)的注释方式,因为Bean的类型信息可以通过Java反射从代码中获取。
  286. 要让JSR-250的注释生效,除了在Bean类中标注这些注释外,还需要在Spring容器中注册一个负责处理这些注释的BeanPostProcessor:
  287. <bean
  288. class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
  289. CommonAnnotationBeanPostProcessor实现了BeanPostProcessor接口,它负责扫描使用了JSR-250注释的Bean,并对它们进行相应的操作。
  290. @PostConstruct@PreDestroy
  291. Spring容器中的Bean是有生命周期的,Spring允许在Bean在初始化完成后以及Bean销毁前执行特定的操作,您既可以通过实现InitializingBean/DisposableBean接口来定制初始化之后/销毁之前的操作方法,也可以通过<bean>元素的init-method/destroy-method属性指定初始化之后/销毁之前调用的操作方法。关于Spring的生命周期,笔者在《精通Spring2.x—企业应用开发精解》第3章进行了详细的描述,有兴趣的读者可以查阅。
  292. JSR-250为初始化之后/销毁之前方法的指定定义了两个注释类,分别是@PostConstruct@PreDestroy,这两个注释只能应用于方法上。标注了@PostConstruct注释的方法将在类实例化后调用,而标注了@PreDestroy的方法将在类销毁之前调用。
  293. 清单17.使用@PostConstruct@PreDestroy注释的Boss.java
  294. packagecom.baobaotao;
  295. importjavax.annotation.Resource;
  296. importjavax.annotation.PostConstruct;
  297. importjavax.annotation.PreDestroy;
  298. publicclassBoss{
  299. @Resource
  300. privateCarcar;
  301. @Resource(name="office")
  302. privateOfficeoffice;
  303. @PostConstruct
  304. publicvoidpostConstruct1(){
  305. System.out.println("postConstruct1");
  306. }
  307. @PreDestroy
  308. publicvoidpreDestroy1(){
  309. System.out.println("preDestroy1");
  310. }
  311. }
  312. 您只需要在方法前标注@PostConstruct@PreDestroy,这些方法就会在Bean初始化后或销毁之前被Spring容器执行了。
  313. 我们知道,不管是通过实现InitializingBean/DisposableBean接口,还是通过<bean>元素的init-method/destroy-method属性进行配置,都只能为Bean指定一个初始化/销毁的方法。但是使用@PostConstruct@PreDestroy注释却可以指定多个初始化/销毁方法,那些被标注@PostConstruct@PreDestroy注释的方法都会在初始化/销毁时被执行。
  314. 通过以下的测试代码,您将可以看到Bean的初始化/销毁方法是如何被执行的:
  315. 清单18.测试类代码
  316. packagecom.baobaotao;
  317. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  318. publicclassAnnoIoCTest{
  319. publicstaticvoidmain(String[]args){
  320. String[]locations={"beans.xml"};
  321. ClassPathXmlApplicationContextctx=
  322. newClassPathXmlApplicationContext(locations);
  323. Bossboss=(Boss)ctx.getBean("boss");
  324. System.out.println(boss);
  325. ctx.destroy();//关闭Spring容器,以触发Bean销毁方法的执行
  326. }
  327. }
  328. 这时,您将看到标注了@PostConstruct的postConstruct1()方法将在Spring容器启动时,创建BossBean的时候被触发执行,而标注了@PreDestroy注释的preDestroy1()方法将在Spring容器关闭前销毁BossBean的时候被触发执行。
  329. 回页首
  330. 使用<context:annotation-config/>简化配置
  331. Spring2.1添加了一个新的context的Schema命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。
  332. 而我们前面所介绍的AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor就是处理这些注释元数据的处理器。但是直接在Spring配置文件中定义这些Bean显得比较笨拙。Spring为我们提供了一种方便的注册这些BeanPostProcessor的方式,这就是<context:annotation-config/>。请看下面的配置:
  333. 清单19.调整beans.xml配置文件
  334. <?xmlversion="1.0"encoding="UTF-8"?>
  335. <beansxmlns="http://www.springframework.org/schema/beans"
  336. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  337. xmlns:context="http://www.springframework.org/schema/context"
  338. xsi:schemaLocation="http://www.springframework.org/schema/beans
  339. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  340. http://www.springframework.org/schema/context
  341. http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  342. <context:annotation-config/>
  343. <beanid="boss"class="com.baobaotao.Boss"/>
  344. <beanid="office"class="com.baobaotao.Office">
  345. <propertyname="officeNo"value="001"/>
  346. </bean>
  347. <beanid="car"class="com.baobaotao.Car"scope="singleton">
  348. <propertyname="brand"value="红旗CA72"/>
  349. <propertyname="price"value="2000"/>
  350. </bean>
  351. </beans>
  352. <context:annotationconfig/>将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor以及equiredAnnotationBeanPostProcessor这4个BeanPostProcessor。
  353. 在配置文件中使用context命名空间之前,必须在<beans>元素中声明context命名空间。
  354. 回页首
  355. 使用@Component
  356. 虽然我们可以通过@Autowired@Resource在Bean类中使用自动注入功能,但是Bean还是在XML文件中通过<bean>进行定义——也就是说,在XML配置文件中定义Bean,通过@Autowired@Resource为Bean的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义Bean,从XML配置文件中完全移除Bean定义的配置呢?答案是肯定的,我们通过Spring2.5提供的@Component注释就可以达到这个目标了。
  357. 下面,我们完全使用注释定义Bean并完成Bean之间装配:
  358. 清单20.使用@Component注释的Car.java
  359. packagecom.baobaotao;
  360. importorg.springframework.stereotype.Component;
  361. @Component
  362. publicclassCar{
  363. }
  364. 仅需要在类定义处,使用@Component注释就可以将一个类定义了Spring容器中的Bean。下面的代码将Office定义为一个Bean:
  365. 清单21.使用@Component注释的Office.java
  366. packagecom.baobaotao;
  367. importorg.springframework.stereotype.Component;
  368. @Component
  369. publicclassOffice{
  370. privateStringofficeNo="001";
  371. }
  372. 这样,我们就可以在Boss类中通过@Autowired注入前面定义的Car和OfficeBean了。
  373. 清单22.使用@Component注释的Boss.java
  374. packagecom.baobaotao;
  375. importorg.springframework.beans.factory.annotation.Autowired;
  376. importorg.springframework.beans.factory.annotation.Required;
  377. importorg.springframework.beans.factory.annotation.Qualifier;
  378. importorg.springframework.stereotype.Component;
  379. @Component("boss")
  380. publicclassBoss{
  381. @Autowired
  382. privateCarcar;
  383. @Autowired
  384. privateOfficeoffice;
  385. }
  386. @Component有一个可选的入参,用于指定Bean的名称,在Boss中,我们就将Bean名称定义为“boss”。一般情况下,Bean都是singleton的,需要注入Bean的地方仅需要通过byType策略就可以自动注入了,所以大可不必指定Bean的名称。
  387. 在使用@Component注释后,Spring容器必须启用类扫描机制以启用注释驱动Bean定义和注释驱动Bean自动注入的策略。Spring2.5对context命名空间进行了扩展,提供了这一功能,请看下面的配置:
  388. 清单23.简化版的beans.xml
  389. <?xmlversion="1.0"encoding="UTF-8"?>
  390. <beansxmlns="http://www.springframework.org/schema/beans"
  391. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  392. xmlns:context="http://www.springframework.org/schema/context"
  393. xsi:schemaLocation="http://www.springframework.org/schema/beans
  394. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  395. http://www.springframework.org/schema/context
  396. http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  397. <context:component-scanbase-package="com.baobaotao"/>
  398. </beans>
  399. 这里,所有通过<bean>元素定义Bean的配置内容已经被移除,仅需要添加一行<context:component-scan/>配置就解决所有问题了——SpringXML配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan/>的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
  400. <context:component-scan/>还允许定义过滤器将基包下的某些类纳入或排除。Spring支持以下4种类型的过滤方式,通过下表说明:
  401. 1.扫描过滤方式
  402. 过滤器类型说明
  403. 注释假如com.baobaotao.SomeAnnotation是一个注释类,我们可以将使用该注释的类过滤出来。
  404. 类名指定通过全限定类名进行过滤,如您可以指定将com.baobaotao.Boss纳入扫描,而将com.baobaotao.Car排除在外。
  405. 正则表达式通过正则表达式定义过滤的类,如下所示:com\.baobaotao\.Default.*
  406. AspectJ表达式通过AspectJ表达式定义过滤的类,如下所示:com.baobaotao..*Service+
  407. 下面是一个简单的例子:
  408. <context:component-scanbase-package="com.baobaotao">
  409. <context:include-filtertype="regex"
  410. expression="com\.baobaotao\.service\..*"/>
  411. <context:exclude-filtertype="aspectj"
  412. expression="com.baobaotao.util..*"/>
  413. </context:component-scan>
  414. 值得注意的是<context:component-scan/>配置项不但启用了对类包进行扫描以实施注释驱动Bean定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),因此当使用<context:component-scan/>后,就可以将<context:annotation-config/>移除了。
  415. 默认情况下通过@Component定义的Bean都是singleton的,如果需要使用其它作用范围的Bean,可以通过@Scope注释来达到目标,如以下代码所示:
  416. 清单24.通过@Scope指定Bean的作用范围
  417. packagecom.baobaotao;
  418. importorg.springframework.context.annotation.Scope;
  419. @Scope("prototype")
  420. @Component("boss")
  421. publicclassBoss{
  422. }
  423. 这样,当从Spring容器中获取bossBean时,每次返回的都是新的实例了。
  424. 回页首
  425. 采用具有特殊语义的注释
  426. Spring2.5中除了提供@Component注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository@Service@Controller。在目前的Spring版本中,这3个注释和@Component是等效的,但是从注释类的命名上,很容易看出这3个注释分别和持久层、业务层和控制层(Web层)相对应。虽然目前这3个注释和@Component相比没有什么新意,但Spring将在以后的版本中为它们添加特殊的功能。所以,如果Web应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用@Repository@Service@Controller对分层中的类进行注释,而用@Component对那些比较中立的类进行注释。
  427. 回页首
  428. 注释配置和XML配置的适用场合
  429. 是否有了这些IOC注释,我们就可以完全摒除原来XML配置的方式呢?答案是否定的。有以下几点原因:
  430. 注释配置不一定在先天上优于XML配置。如果Bean的依赖关系是固定的,(如Service使用了哪几个DAO类),这种配置信息不会在部署时发生调整,那么注释配置优于XML配置;反之如果这种依赖关系会在部署时发生调整,XML配置显然又优于注释配置,因为注释是对Java源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
  431. 如果Bean不是自己编写的类(如JdbcTemplate、SessionFactoryBean等),注释配置将无法实施,此时XML配置是唯一可用的方式。
  432. 注释配置往往是类级别的,而XML配置则可以表现得更加灵活。比如相比于@Transaction事务注释,使用aop/tx命名空间的事务配置更加灵活和简单。
  433. 所以在实现应用中,我们往往需要同时使用注释配置和XML配置,对于类级别且不会发生变动的配置可以优先考虑注释配置;而对于那些第三方类以及容易发生调整的配置则应优先考虑使用XML配置。Spring会在具体实施Bean创建和Bean注入之前将这两种配置方式的元信息融合在一起。
  434. 回页首
  435. 小结
  436. Spring在2.1以后对注释配置提供了强力的支持,注释配置功能成为Spring2.5的最大的亮点之一。合理地使用Spring2.5的注释配置,可以有效减少配置的工作量,提高程序的内聚性。但是这并不意味着传统XML配置将走向消亡,在第三方类Bean的配置,以及那些诸如数据源、缓存池、持久层操作模板类、事务管理等内容的配置上,XML配置依然拥有不可替代的地位。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics