spring 注解讲的最详细的文章:
http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/
根据属性名自动注入, 需要配置一个后置处理器:
然后就可以在属性定义上加上@Autowired了
不过属性不能定义为静态的, 否则会报错
默认的自动注入会在加载的时候就初始化, 如果不想一开始就初始化, 可以这样写:@Autowired(required = false)
因为是根据属性名字注入的, 如果属性名字和配置的bean名字不同, 则需要借助另外一个注解:@Qualifier, 比如这样写:
@Autowired
@Qualifier("officeOne")
private Office office;
还有一种处理办法是使用@Resource注解:
// 自动注入 bean 名称为 officeOne 的 Bean
@Resource(name = "officeOne")
private Office office;
要让这个注解生效, 需要配置这样的后置处理器:
注解后置处理器也可以简化一下, 比如这样配置:
他实际上会配置四个注解后置处理器:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor
完全取消bean配置的做法, 就是使用 @Component
但是还必须后一个配置告诉spring容器扫描所有的类是否带有该注解:
该配置隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor, 所以可以去掉<context:annotation-config/>配置
http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/
根据属性名自动注入, 需要配置一个后置处理器:
<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
然后就可以在属性定义上加上@Autowired了
不过属性不能定义为静态的, 否则会报错
默认的自动注入会在加载的时候就初始化, 如果不想一开始就初始化, 可以这样写:@Autowired(required = false)
因为是根据属性名字注入的, 如果属性名字和配置的bean名字不同, 则需要借助另外一个注解:@Qualifier, 比如这样写:
@Autowired
@Qualifier("officeOne")
private Office office;
还有一种处理办法是使用@Resource注解:
// 自动注入 bean 名称为 officeOne 的 Bean
@Resource(name = "officeOne")
private Office office;
要让这个注解生效, 需要配置这样的后置处理器:
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
注解后置处理器也可以简化一下, 比如这样配置:
<?xml version="1.0" encoding="UTF-8" ?>
<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/>
....其他bean配置
</beans>
他实际上会配置四个注解后置处理器:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor
完全取消bean配置的做法, 就是使用 @Component
但是还必须后一个配置告诉spring容器扫描所有的类是否带有该注解:
<?xml version="1.0" encoding="UTF-8" ?>
<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:component-scan base-package="com.baobaotao"/>
</beans>
该配置隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor, 所以可以去掉<context:annotation-config/>配置