Easy java spring

What is a Spring bean, and how do @Component, @Service, @Repository and @Bean differ?

The 30 second answer

A bean is an object that the Spring container creates, wires and manages. @Component marks a class so component scanning picks it up; @Service and @Repository are specialised @Components that state the layer, and @Repository also turns database exceptions into Spring's DataAccessException. @Bean is different: it goes on a method in a @Configuration class and returns an object I build myself, which is how I register third-party classes I can't annotate.

<!-- level: 1 --> <!-- must_know: true -->

A bean is any object whose lifecycle the Spring IoC container manages: it creates it, injects its dependencies, calls its init and destroy callbacks, and hands it to other beans.

There are two common ways to register one:

1. Component scanning with stereotype annotations. Spring scans packages (by default the package of your @SpringBootApplication class and below) and registers every class annotated with:

  • @Component: the generic stereotype.
  • @Service: a @Component for business logic. It adds no behaviour today; it documents intent.
  • @Repository: a @Component for data access. The Spring reference notes it is also eligible for automatic persistence exception translation, so vendor exceptions become Spring's DataAccessException hierarchy.
  • @Controller / @RestController: a @Component for the web layer.

**2. @Bean methods.** In a @Configuration class, a method annotated with @Bean returns an object that becomes a bean. Use this for classes you don't own (a client from a library), or when building the object needs logic.

@Configuration
public class HttpConfig {
    @Bean
    public RestClient paymentsClient() {
        return RestClient.builder().baseUrl("https://payments.internal").build();
    }
}
Sources (2)
  1. Spring Framework: Classpath scanning and managed componentsdocs.spring.io
  2. Spring Framework: Using the @Bean annotationdocs.spring.io