Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-12

What is the difference between @Component and @Bean?

Options

  1. There is no difference; both register a bean the same way
  2. @Component scans your class; @Bean uses a method result (Correct option)
  3. @Bean is meant for tests only, not for production code
  4. @Component can only be placed on interfaces, not classes

Answer

@Component goes on a class you own and is found by scanning; @Bean goes on a method inside a @Configuration class and registers the returned object, useful for third-party classes

Why

@Component (and its stereotypes) annotates your own class, and Spring discovers it by component scanning.

@Bean is placed on a method in a @Configuration class. The returned object is registered as a bean. Use it when you cannot annotate the class (a library class like ObjectMapper or RestClient) or when construction needs custom logic.

@Configuration
public class AppConfig {
    @Bean
    public Clock clock() {
        return Clock.systemUTC();
    }
}

Remember

@Component = my class. @Bean = a factory method for any class.

Key terms

Practice this question in Repaso