Skip to main content

Command Palette

Search for a command to run...

Diff between @Bean & @Component

Updated
1 min read

Both @Bean and @Component are ways to tell spring ioc container “Hey, i want u to manage these object for me”.

@Component is a class-level annotation. Its basically telling ioc container “during your startup scan, when u meet this class, please initiate it and keep it in your pocket”

  • Sterotypes:

    • @Controller: for web request handler

    • @Service: for business logic

    • @Repository: for data access

  • Best for: you own the source code and have full control over the code

@Bean is a method-level annotation. Usually found in a class marked with @Configuration. Instead of spring find the class and do the job, you write code to initialize it and return it.

  • Best for: third party libaries where we have no access to the source code so that we can not annotate with @Component'