一我的理解是Annotation方式是辅助XML配置的方式,它在属性,方法,构造方法上增加注解,用来注入这些属性、方法和完成
构造方法的初始化。而类的实例化仍然要是用xml中配置。如
<bean id="now" class="java.util.Date"/>
二
1.
@Autowired @Qualifier("random") Random rnd; //@Autowired使用类型名进行注入,而加上@Qualifier("random")就是使用名字进行注入。
2.
@Resource SimpleDateFormat sf;//默认是通过属性名字,也就是这里的sf进行注入。 @Resource(name="simpleDateFormat") SimpleDateFormat sf; /*这里是让注解处理器到容器中去寻找名为simpleDateFormat的实例,如果我们的实例名指向的实例名字相同,就直接使用 @Resource,因为它默认就是按照名字进行注入,如果在容器中找不到,则使用该实例的类型去找。 */
3.
@PostConstruct public void init() { System.out.println("AnnotationIocBean被实例化了!"); } //@PostConstruct相当于构造方法
4.
@PreDestroy public void destroy() { System.out.println("AnnotationIocBean实例被销毁了!"); } //使用@PreDestroy注解指定实例销毁时调用的方法
三使用Annotation方式的bean装配需要哪些步骤
1.导入common-annotations.jar。
2.在Spring配置文件中定义context命名空间和相应的schemaLocation
<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"> </beans>
3.在Spring配置文件中开启相应的注解处理器。
<context:annotation-config/>
4.在Bean中使用注解
可参见http://book.51cto.com/art/201004/193747.htm