Spring Bean

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 @Configuration class 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.properties or application.yml into 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

  1. Instantiation → Spring creates the bean.
  2. Dependency Injection → Required dependencies are injected.
  3. Initialization@PostConstruct or InitializingBean.afterPropertiesSet().
  4. Usage → Bean is available for use.
  5. Destruction → On app shutdown, @PreDestroy or DisposableBean.destroy() is called.

Leave a Reply