SteelReed

Search

Search posts, questions…

Spring BootQuestion 2 / 26

Junior

How do @Component, @Service, @Repository and @Bean differ? How is @Configuration different from @Component?

Short answer

@Service, @Repository, @Controller are @Component with a role, and scanning creates the bean. @Bean goes on a method, for classes you can't edit or that need custom setup; @Configuration gets a CGLIB proxy, so cross-calls between @Bean methods still return the singleton.

yes, editableexternal librarycross-call @Bean methodIs the class yours?@Service, @Repository...scan creates it@Bean inside@ConfigurationCGLIB proxykeeps singleton

3 points to say:

  1. @Service/@Repository/@Controller are role-flavored @Components; @Repository translates exceptions to DataAccessException.
  2. @Bean is for external classes or custom initialization.
  3. @Configuration is proxied to keep singletons on cross-method calls; @Bean methods in a @Component are lite mode, without a proxy.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.