HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring MVC / Spring MVC: <context:annotation-config> vs <context:component-scan>

Spring MVC: <context:annotation-config> vs <context:component-scan>

We have already learned few things in Spring MVC in previous posts. In those tutorials, I did use tags like <context:annotation-config> or <context:component-scan>, but I didn’t explained much in detail about these tags. I am writing this post, specifically to list down the difference between tags <context:annotation-config> and <context:component-scan> so that when you use them in future, you will know, what exactly are you doing.

1) First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g. using <context:component-scan> or it was defined in application-context.xml file itself.

2) Second difference is driven from first difference itself. It does register the beans in context + it also scans the annotations inside beans and activate them. So <context:component-scan>; does what <context:annotation-config> does, but additionally it scan the packages and register the beans in application context.

Example of <context:annotation-config> vs <context:component-scan> uses

I will elaborate both tags in detail with some examples which will make more sense to us. For keeping the example to simple, I am creating just 3 beans, and I will try to configure them in configuration file in various ways, then we will see the difference between various configurations in console where output will get printed.

For reference, below are 3 beans. BeanA has reference to BeanB and BeanC additionally.

package com.howtodoinjava.beans;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@SuppressWarnings("unused")
@Component
public class BeanA {
	
	private BeanB beanB;
	private BeanC beanC;
	
	public BeanA(){
		System.out.println("Creating bean BeanA");
	}

	@Autowired
	public void setBeanB(BeanB beanB) {
		System.out.println("Setting bean reference for BeanB");
		this.beanB = beanB;
	}

	@Autowired
	public void setBeanC(BeanC beanC) {
		System.out.println("Setting bean reference for BeanC");
		this.beanC = beanC;
	}
}

//Bean B

package com.howtodoinjava.beans;

import org.springframework.stereotype.Component;

@Component
public class BeanB {
	public BeanB(){
		System.out.println("Creating bean BeanB");
	}
}

//Bean C

package com.howtodoinjava.beans;

import org.springframework.stereotype.Component;

@Component
public class BeanC {
	public BeanC(){
		System.out.println("Creating bean BeanC");
	}
}

BeanDemo class is used to load and initialize the application context.

package com.howtodoinjava.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanDemo {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
	}
}

Now let’s start writing the configuration file "beans.xml" with variations. I will be omitting the schema declarations in below examples, to keep focus on configuration itself.

a) Define only bean tags

<bean id="beanA" class="com.howtodoinjava.beans.BeanA"></bean>
<bean id="beanB" class="com.howtodoinjava.beans.BeanB"></bean>
<bean id="beanC" class="com.howtodoinjava.beans.BeanC"></bean>

Output:

Creating bean BeanA
Creating bean BeanB
Creating bean BeanC

In this case, all 3 beans are created and no dependency in injected in BeanA because we didn’t used any property/ref attributes.

b) Define bean tags and property ref attributes

<bean id="beanA" class="com.howtodoinjava.beans.BeanA">
	<property name="beanB" ref="beanB"></property>
	<property name="beanC" ref="beanC"></property>
</bean>
<bean id="beanB" class="com.howtodoinjava.beans.BeanB"></bean>
<bean id="beanC" class="com.howtodoinjava.beans.BeanC"></bean>

Output:

Creating bean BeanA
Creating bean BeanB
Creating bean BeanC
Setting bean reference for BeanB
Setting bean reference for BeanC

Now the beans are created and injected as well. No wonder.

c) Using only <context:annotation-config />

<context:annotation-config />

//No Output

As I told already, <context:annotation-config /> activate the annotations only on beans which have already been discovered and registered. Here, we have not discovered any bean so nothing happened.

d) Using <context:annotation-config /> with bean declarations

<context:annotation-config />
<bean id="beanA" class="com.howtodoinjava.beans.BeanA"></bean>
<bean id="beanB" class="com.howtodoinjava.beans.BeanB"></bean>
<bean id="beanC" class="com.howtodoinjava.beans.BeanC"></bean>

Output:

Creating bean BeanA
Creating bean BeanB
Setting bean reference for BeanB
Creating bean BeanC
Setting bean reference for BeanC

In above configuration, we have discovered the beans using <bean> tags. Now when we use <context:annotation-config />, it simply activates @Autowired annotation and bean injection inside BeanA happens.

e) Using only <context:component-scan />

<context:component-scan base-package="com.howtodoinjava.beans" />

Output:

Creating bean BeanA
Creating bean BeanB
Setting bean reference for BeanB
Creating bean BeanC
Setting bean reference for BeanC

Above configuration does both things as I mentioned earlier in start of post. It does the bean discovery (searches for @Component annotation in base package) and then activates the additional annotations (e.g. Autowired).

f) Using both <context:component-scan /> and <context:annotation-config />

<context:annotation-config />
<context:component-scan base-package="com.howtodoinjava.beans" />
<bean id="beanA" class="com.howtodoinjava.beans.BeanA"></bean>
<bean id="beanB" class="com.howtodoinjava.beans.BeanB"></bean>
<bean id="beanC" class="com.howtodoinjava.beans.BeanC"></bean>

Output:

Creating bean BeanA
Creating bean BeanB
Setting bean reference for BeanB
Creating bean BeanC
Setting bean reference for BeanC
Strange !! With above configuration we are discovering beans two times and activating annotations two times as well. But output got printed one time only. Why? Because spring is intelligent enough to register any configuration processing only once if it is registered multiple tiles using same or different ways. Cool !!

So, Here i am ending this tutorial and hoping that it will give a more clear picture to you guys when you use these tags in your next project. Feel free to download the sourcecode and play with it.

Download Sourcecode

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. akhil

    April 2, 2020

    Seriously ..that called an explanation

  2. zws

    March 8, 2020

    appreciate your work by real world example!Thank you very much!

  3. alice

    July 10, 2019

    Wow good examples… thanks!

  4. babji

    December 17, 2018

    Very nice explanation Thanks

  5. Rahul

    December 12, 2018

    <bean id="beanA" class="com.howtodoinjava.beans.BeanA">
        <property name="beanB" ref="beanB"></property>
        <property name="beanC" ref="beanC"></property>
    </bean>
    <bean id="beanB" class="com.howtodoinjava.beans.BeanB"></bean>
    <bean id="beanC" class="com.howtodoinjava.beans.BeanC"></bean>
     

    In this why are both the beans B and C created first and then property assigned to bean A ? it is different than autowired .

  6. Sanjay

    October 7, 2018

    Thank you for providing examples, which are very helping in understanding the topic rather than just theory…
    Can you please also tell what is the purpose of

  7. rakesh

    September 7, 2017

    very good explanation I don’t feel we can any better than this

  8. Niroop

    June 22, 2017

    Finally, understood with the examples provided. very nice explanation thank you very much .. and nice job..!

  9. Ani

    March 7, 2017

    Very well explained indeed !

  10. Sriram

    January 27, 2017

    Good article for Spring Noobs. Finally, understood with the examples provided.
    Thank you.

  11. Dhrumil

    September 29, 2016

    Thanks nice explanation…

  12. Banu

    August 13, 2016

    super it is very useful for me

    • Banu

      August 13, 2016

      And neat crystal clear explanation

  13. lanka phani

    November 12, 2015

    java.very nice explination

  14. srinivas

    June 27, 2015

    nice explanation…… very useful

  15. Mateen

    May 8, 2015

    excellent post. Everything is crystal clear but even though i need to execute these examples for better confidence. Thanks for the post it was really very helpful.

  16. Karan Kaw

    March 14, 2015

    Great Artcile written in 2011, Very useful

    https://stackoverflow.com/questions/7414794/difference-between-contextannotation-config-and-contextcomponent-scan

  17. sadhan

    November 13, 2014

    how to send sms from web application by using java (spring framework). Please don’t refer me JMS you can suggest me other than JMS. Send me code details.

  18. mhewedy

    October 26, 2014

    From the context XSD namespace “Defines the configuration elements for the Spring Framework’s application context support. Effects the activation of various configuration styles for the containing Spring ApplicationContext.”

    Which means, this two annotations are spring-mvc agnostic, and they are Spring framework related

    • Lokesh Gupta

      October 27, 2014

      Hmmm.. Yes you are right. They are Spring framework related.

  19. rampal

    July 19, 2014

    Interesting post!!!! So does it means that entry (along with package values) alone would suffice in the configuration file?

    • Lokesh Gupta

      July 19, 2014

      Depends what you want to achieve. I am not saying what is sufficient or not. I just wanted to inform the meaning and effect of various tags when mentioned inside configuration file.

      • rampal

        July 19, 2014

        I think something was missed out of my earlier comment. It is mentioned in the post that context:component-scan does what context:annotation-config does, but additionally it scan the packages and register the beans in application context. So can we omit annotation config from my configuration file if component scan is there.

        • Lokesh Gupta

          July 19, 2014

          Yes, absolutely correct.

Comments are closed on this article!

Search Tutorials

Spring MVC Tutorial

  • MVC – Introduction
  • MVC – Hello World
  • MVC – JSTL
  • MVC – @RequestMapping
  • MVC – Custom Validator
  • MVC – JSR-303 Validation
  • MVC – Dropdown
  • MVC – Submit Form
  • MVC – MessageSourceAware
  • MVC – XmlViewResolver
  • MVC – i18n and i10n
  • MVC – Interceptor
  • MVC – HandlerInterceptor
  • MVC – Multi File Upload (Ajax)
  • MVC – Multi File Upload
  • MVC – File Download
  • MVC – Interview Questions
  • InternalResourceViewResolver
  • ResourceBundleViewResolver
  • SimpleMappingExceptionResolver
  • annotation-config vs component-scan
  • ContextLoaderListener vs DispatcherServlet

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)