annotation-config和component-scan

  以前学到<context:annotation-config></context:annotation-config>和<context:component-scan base-package="" ></context:component-scan>和两个配置的时候,只知道,annotation-config是用来开启xml配置中的bean对注解的支持,而component-scan是用来开启注解扫描,扫描指定包下面带注解的类。

  今天看源码有了点新的收获:

    annotation-config这个标签,实际上是注册各种BeanPostProcesser到BeanFactory,比如:AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor这些,看名字就知道是干啥的了,因此xml配置的bean也就能通过注解注入了。

    context:component-scan标签,实际是将配置的类路径转换为文件路径,比如:base-package="com.zby",转换为classpath*:com/zby/**/*.class,然后把这些加载的字节码封装成Resource,通过ASM读取字节码信息,封装成ScannedGenericBeanDefinition。这样就可以注册到BeanFactory了。同时,component-scan标签包含了annotation-config的功能,也注册了一系列对注解支持的BeanPostProcesser,所以,就不要同时出现这两个标签了。

    看到这儿,也终于解决一个困惑,之前一直不知道asm在spring用来干嘛的,asm是用来扫描包,解析字节码的,cglib用来做代理增强。

posted @ 2018-04-23 17:41  java拌饭  阅读(215)  评论(0编辑  收藏  举报