Wednesday, August 28, 2013

Difference between context:component-scan and context:annotation-config in Spring

<context:component-scan/> scan packages and classes within given base packages then find and register beans into ApplicationContext.It does all things that <context:annotation-config/> is supposed to do.
So if you have used annotation for example, @Autowired in your code and <context:component-scan/> in xml then You do not require to use <context:annotation-config/>


<context:annotation-config /> only works on bean which are already registered on ApplicationContext.Doesn't matter they were registered using xml or annotations.And it's for only some of annotation which I have mentioned below.  So If you have used @Autowired in your code and beans are registered either using xml or @Configuration then you can use <contex:annotationconfig/>.

<context:annotation-config />  registers only 4 BeanPostProcessors which are part of the Spring Framework and They are follows as :

1. CommonAnnotationBeanPostProcessor :
Recognizes and processes the JSR 250 common annotations (@PostConstruct, @PreDestroy, @Resource)

2. AutowiredAnnotationBeanPostProcessor
Recognizes the Autowired related annotations (@Autowired, @Value, @Inject, @Qualifier, etc)

3. RequiredAnnotationBeanPostProcessor :
Recognizes the @Required annotation

4. PersistenceAnnotationBeanPostProcessor :
Recognizes the @PersistenceUnit and @PersistenceContext annotations (related to JPA) etc.

If I have missed any annotationPostProcessor here then let me know. 

<context:component-scan/> annotation is a super set of the <context:annotation-config/> meaning it registers all those bean post processors which are mentioned above with addition of other annotation and also scan classes which are annotated with category of annotations (@Component, @Repository, @Controller, etc).

You should either use only one, I usually prefer to use <context:component-scan/>

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/