spring之使用@Autowired和@Resource自动装配Bean(1)
----------
Spring2.5对自动装配特性进行了增强。可以通过注解setter方法、构造器、字段、基于任意方法来自动装配特定的属性,可以使用@Autowired注解,也可以使用JSR-250规范中定义的@Resource注解。不过基于注解的方式需要使用java1.5或更高的版本。
要让Spring自动装配具有@Autowired或@Resource的Bean属性,首先必须在IOC容器里注册AutowiredAnnotationBeanPostProcessor实例。如果使用的是Bean Factory,则必须通过API注册该Bean后置处理器。否则,则只需要在应用程序上下文里声明一下即可。
<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor"/>
更简单一点,可以在Bean配置文件里包含<context:annotation-config>元素,此时,AutowiredAnnotationBeanPostProcessor实例将会被自动注册。 \
<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/> ... </beans>