spring配置中《context:annotation-config》 和 《context:component-scan》区别

看到网上有很多大神的文章讲解,讲得很好很深,可是我没有用到过,理解不了,在这写一点我自己理解的区别。

如果想使用@AutoWired注解,需要在Spring配置文件中配置<context:annotation-config> 。

<context:annotation-config>做了什么呢?

他的作用是向 Spring 容器注册了以下4个BeanPostProcessor

AutowiredAnnotationBeanPostProcessor、                        @Autowired    

CommonAnnotationBeanPostProcessor、                         @ Resource 、@ PostConstruct、@ PreDestroy

PersistenceAnnotationBeanPostProcessor 、                    @PersistenceContext

RequiredAnnotationBeanPostProcessor、                         @Required

注册这4个 BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解

但是通常情况下,我们是不需要在写<context:annotation-config>的,因为使用Spring时一般都会使用<context:component-scan>把添加了@Service或者@Controller注解的类加到Spring容器中,那么

<context:component-scan>做了什么呢?

 <context:component-scan>做了两件事:

1. 把<context:annotation-config>做的事都做了(注册了4个BeanPostProcessor

2. 扫描出需要的类到Spring容器中

把这两个注解的含义捋清楚之后,可以帮助理解和使用Spring,不懂得可以留言讨论。

猜你喜欢

转载自blog.csdn.net/hcrw01/article/details/82858813
今日推荐