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@Componentfor business logic. It adds no behaviour today; it documents intent.@Repository: a@Componentfor data access. The Spring reference notes it is also eligible for automatic persistence exception translation, so vendor exceptions become Spring'sDataAccessExceptionhierarchy.@Controller/@RestController: a@Componentfor 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)
- Spring Framework: Classpath scanning and managed componentsdocs.spring.io
- Spring Framework: Using the @Bean annotationdocs.spring.io