WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Advanced · question 43 of 100

Explain the difference between @Bean and @Component annotations in Spring.?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

In the Spring Framework, both ‘@Bean‘ and ‘@Component‘ annotations are used to declare beans, but they have different purposes and use cases.

‘@Component‘ is a stereotype annotation that identifies a class as a Spring-managed component. This annotation tells Spring to create a bean instance of the annotated class and register it in the application context. Spring will automatically detect and create instances of all classes annotated with ‘@Component‘ when it scans the project’s classpath. For example, the following code snippet shows how to use ‘@Component‘ annotation to create a bean instance of a class:

@Component
public class MyComponent {
    // class implementation
}

On the other hand, the ‘@Bean‘ annotation is used to explicitly declare a bean instance in a Java configuration class. This annotation is used in conjunction with a method that produces a bean instance when invoked. The method annotated with ‘@Bean‘ creates and returns the instance of the bean, and Spring manages it in the application context. For example, the following code shows how to use ‘@Bean‘ annotation to manually create a bean instance in a configuration class:

@Configuration
public class MyConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

As you can see from the above code snippet, ‘@Bean‘ tells Spring that the method ‘myBean()‘ will produce a bean instance, and Spring manages the instance in the application context.

In summary, ‘@Component‘ is used for automatic bean detection and registration, while ‘@Bean‘ is used for manual bean declaration and configuration.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics