In Spring Boot, a bean is simply an object managed by the Spring IoC (Inversion of Control) container. Beans are the backbone of any Spring-based application. Spring automatically creates, wires, and manages their lifecycle, so you don’t need to manually instantiate or manage dependencies.
🔑 Ways to Define Beans in Spring Boot
1. Using @Component and Stereotype Annotations
- Mark your class with
@Component(or@Service,@Repository,@Controller). - Spring Boot scans the classpath (thanks to
@SpringBootApplication→@ComponentScan) and automatically registers them as beans.
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public String sayHello() {
return "Hello from MyBean!";
}
}
You can then inject this bean wherever needed:
import org.springframework.stereotype.Service;
@Service
public class MyService {
private final MyBean myBean;
public MyService(MyBean myBean) {
this.myBean = myBean;
}
public void doWork() {
System.out.println(myBean.sayHello());
}
}
2. Using @Bean in a Configuration Class
- Define beans manually inside a
@Configurationclass with@Bean.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
3. Using External Configuration (Properties + @ConfigurationProperties)
- You can bind values from
application.propertiesorapplication.ymlinto beans.
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int version;
// getters & setters
}
application.yml
app:
name: MySpringApp
version: 1
4. Conditional Beans
You can control bean creation with annotations like:
@ConditionalOnProperty@Profile@ConditionalOnMissingBean
@Bean
@ConditionalOnProperty(name = "featureX.enabled", havingValue = "true")
public FeatureX featureX() {
return new FeatureX();
}
🔄 Bean Lifecycle in Spring Boot
- Instantiation → Spring creates the bean.
- Dependency Injection → Required dependencies are injected.
- Initialization →
@PostConstructorInitializingBean.afterPropertiesSet(). - Usage → Bean is available for use.
- Destruction → On app shutdown,
@PreDestroyorDisposableBean.destroy()is called.
