What is the difference between @Configuration and @Component in Spring?

@ComponentScan creates beans using both @Configuration and @Component. Both these annotations work fine when swapped. What is the difference then?


Solution 1:

@Configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime

@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning

You can see more here:

http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html

A @Configuration is also a @Component, but a @Component cannot act like a @Configuration.

Solution 2:

Actually answer is not complete, is it true that:

@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

But you do can create i.e MyConfiguration.java class then stereotype with @Component and add @Beans declaration to it. In this way it will looks as a configuration, main difference is that when annotated class with @Configuration @Bean annotated methods are proxy using CGLIB which made in code calls after the first one to return bean from context instead of execute method again and create another instance as happens when using @Component with @Bean

Solution 3:

@Configuration - It is like beans.xml but Java-based bean configuration. It means class annotated with this annotation is the place where beans are configured and will be a candidate for auto-detection. In this class, methods are annotated with @Bean which return an object of the class.

Example:

@Configuration
public class ConfigClass {

    @Bean
    public UserClass getObject() {
        return new UserClass();
    }
}

@Component - You cannot autowire (@Autowired) any class if it is not marked with @Component. It means when you want to autowire any class using annotation that class should be annotated with @Component.

Example:

@Component
public class A { .... }

public class B { 
    @Autowired
    A a;
    .....
    .....
}

Spring Document for reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html