spring 注解学习笔记

spring 注解讲的最详细的文章:
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/>配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值