1. 程式人生 > >spring配置中《context:annotation-config》 和 《context:component-scan》區別

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,不懂得可以留言討論。