Clean ⢠Professional
In Spring Boot, a bean is an object that is instantiated, configured, and managed by the Spring IoC container. Beans form the core of any Spring Boot application, enabling dependency injection (DI), loose coupling, and modular design.
A Spring Boot bean is:
new.Ways to create a bean:
@Component, @Service, @Repository, @Controller, @RestController@Configuration classesExample:
@Service
public class UserService {
public void createUser() {
System.out.println("User created");
}
}
Here, UserService is a Spring-managed bean that can be injected into other components.
Bean scopes define the lifecycle and visibility of a bean.
| Scope | Description |
|---|---|
| Singleton | Default scope. One instance per Spring IoC container. |
| Prototype | New instance every time requested from the container. |
| Request | One instance per HTTP request (web apps). |
| Session | One instance per HTTP session. |
| Application | One instance per ServletContext. |
| Websocket | One instance per WebSocket session. |
Example ā Singleton Bean:
@Component
@Scope("singleton")
public class MySingletonBean { }
Default scope is Singleton, which is ideal for shared services.
In Spring Boot, beans are created and managed automatically by the Spring IoC container. Bean creation happens during application startup and follows a well-defined process.
Spring Boot scans packages starting from the main class annotated with @SpringBootApplication.
It detects classes annotated with:
@Component@Service@Repository@Controller@RestControllerExample:
@Service
publicclassUserService {
}
ā”ļø Spring automatically creates a UserService bean.
@BeanBeans can be explicitly defined inside a @Configuration class.
Used when:
Example:
@Configuration
publicclassAppConfig {
@Bean
public RestTemplaterestTemplate() {
returnnewRestTemplate();
}
}
ā”ļø Spring registers RestTemplate as a bean.
Spring Boot automatically creates beans based on:
Examples:
DataSourceEntityManagerFactoryDispatcherServletPowered by:
@EnableAutoConfigurationspring.factoriesAutoConfiguration.importsā”ļø No manual configuration needed.
Beans are created only if certain conditions are met.
Common conditions:
@ConditionalOnClass@ConditionalOnMissingBean@ConditionalOnPropertyExample:
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public FeatureServicefeatureService() {
returnnewFeatureService();
}
Beans can be loaded for specific environments.
Example:
@Service
@Profile("dev")
publicclassDevMailService {
}
ā”ļø Bean created only when spring.profiles.active=dev.
Beans are created only when requested, not at startup.
@Component
@Lazy
publicclassReportService {
}
Used when bean creation logic is complex.
@Component
publicclassMyFactoryimplementsFactoryBean<MyObject> {
public MyObjectgetObject() {
returnnewMyObject();
}
}
ApplicationStarts
ā
ComponentScan / @Bean /Auto-Config
ā
BeanDefinitionsRegistered
ā
BeanInstantiation
ā
DependencyInjection
ā
Initialization (@PostConstruct)
ā
BeanReadyforUse
Spring Boot automatically injects dependencies into beans. DI types include:
Constructor Injection
@Service
public class OrderService {
private final PaymentService paymentService;
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
Setter Injection
@Service
public class OrderService {
private PaymentService paymentService;
@Autowired
public void setPaymentService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
Field Injection
@Service
public class OrderService {
@Autowired
private PaymentService paymentService;
}
Best Practice: Prefer constructor injection for mandatory dependencies to improve testability and immutability.
Spring manages the full lifecycle of a bean:
BeanNameAware, ApplicationContextAware.@PostConstruct or InitializingBean.@PreDestroy or DisposableBean.Example:
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
@PreDestroy
public void cleanup() {
System.out.println("Bean destroyed");
}
}
@Component
@Lazy
public class LazyBean { }
Beans can be created conditionally based on properties or environment:
@Bean
@ConditionalOnProperty(name="feature.enabled", havingValue="true")
public FeatureService featureService() {
return new FeatureService();
}
Spring can inject all beans of a type into a collection:
@Autowired
private List<NotificationService> notificationServices;
This allows handling multiple implementations of a service interface.
Service Bean
@Service
public class EmailService implements NotificationService {
public void notifyUser(String user) {
System.out.println("Email sent to " + user);
}
}
Controller Bean
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public String getUser(@PathVariable String id) {
return "User ID: " + id;
}
}
@Component, @Service, @Repository, @Controller, @RestController for automatic scanning@Bean in @Configuration classes for manual definition