annotation之context:annotation-config与 context:component-scan的区别与联系

注解的作用基本有三个:
1、生成文档:是java 最早提供的注解。常用的有 @see @param @return 等
2、跟踪代码依赖性,实现替代配置文件功能:比较常见的是spring 2.5 开始的基于注解配置。作用就是减少配置。现在的框架基本都使用了这种配置来减少配置文件的数量。
3、在编译时进行格式检查:如@override 放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出。

附:java注解的知识网络


一、共同点

扫描注解,替代get/set方法,完成自动注入

二、不同点

1、 <context:annotation-config/>只扫描注解,不负责创建javabean;只有当自己在xml中手动配置bean后,手动创建的bean已经被注册到spring容器里,才能实现自动注入;

2、 <context:component-scan base-package=url/>可以扫描注解;其base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会可以创建扫描包下的Javabean,即有这一个配置后,就不用再手动配置bean,只要需要的bean在扫描包下就可以利用注解实现自动注入;概括就是:可以自动将base-package配置包及其递归子包下的类自动创建bean并注册到spring容器中,还能扫描注解,扫描到需要装配的节点时,代替get/set方法自动注入到所需类的属性中;

:配置了 <context:annotation-config/>或 <context:component-scan/>后,系统之所以能够识别相应的注解,是因为此配置隐式的向 Spring 容器注册了

AutowiredAnnotationBeanPostProcessor、

CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor 、

 RequiredAnnotationBeanPostProcessor

 这 4 个BeanPostProcessor ,如果手动配置如下:

@Autowired

 <bean class= "org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

@ Resource 、@ PostConstruct、@ PreDestroy

<bean class= "org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor" />

@PersistenceContext

<bean class= "org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor " />

@Required
<bean class= "org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

注:如果在配置文件中配置了<context:component-scan />,就不用在配置<context:annotation-config/>,因为前者已经包含了后者。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值