之前讲了xml中的autowire,是在被注入的bean上写autowire=“byName”当然还可以byType,default等等。
当然autowire这句话可以放到annotation中,这样的好处是
1、xml中的bean特别的整洁,每一行写一个bean,没有bean之间相互注入的关系,没有autowire的补丁。
2、由于整洁,可以只让程序员只关注bean,而把关系放到annotation中,这样更有条理。bean负责生成类的实例,注入由annotation负责
需要用到上一个例子
[url=/admin/blogs/2109324]使用xml的autowire[/url]
现在修改springbean.xml为下面这个样子
新增命名空间的配置。
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
新增了<context:annotation-config></context:annotation-config>标签,表示使用注释的方式进行配置。
同时删除掉xml文件中userService bean的autowire的配置。
在UserService类setDao方法上面增加@Autowired
测试一下,还是不行,因为使用annotation需要导入一个jar包
现在导入common-annotations.jar
导入后入下图。
[img]http://dl2.iteye.com/upload/attachment/0100/5887/904a5327-bfca-3363-83da-eada12601ef8.png[/img]
再测试一下,就ok了
[color=red]从现在起都提供源代码以供参考。请自行下载源码吧[/color]