Search code examples
javaspringspring-3

difference between @Component and @Configuration in Spring 3


I came across two annotations provided by Spring 3 (@Component and @Configuration) I am a bit confused between these.
Here is what I read about @Component

Put this “context:component” in the bean configuration file, it means, enable the auto-scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.

So I am wondering what is the use of @Configuration then if @Controller will register my beans without the need to declare them in the spring configuration XML file.


Solution

  • @Configuration is the heart of the Java-based configuration mechanism that was introduced in Spring 3. It provides an alternative to XML-based configuration.

    So the 2 following snippets are identical:

    <beans ...>
        <context:component-scan base-package="my.base.package"/>
        ... other configuration ...
    </beans>
    

    and:

    @Configuration
    @ComponentScan(basePackages = "my.base.package")
    public class RootConfig {
        ... other configuration ...
    }
    

    In both cases Spring will scan in my.base.package and below for classes annotated with @Component or one of the other annotations that are meta-annotated with @Component such as @Service.