✅ Spring Bean Exceptions – Complete Notes (Spring Boot)




1️⃣ Introduction


In **Spring Boot**, Beans are objects managed by the **Spring IoC Container**.


Whenever Spring fails to:


- Create a bean

- Inject a dependency

- Initialize the context

- Resolve configuration

- Wire dependencies


It throws **Bean-related Exceptions**.


Understanding these exceptions is critical for:


- Debugging startup failures

- Fixing dependency injection issues

- Interview preparation

- Production troubleshooting




2️⃣ Where Do Bean Exceptions Occur?


Bean exceptions typically occur during:


Application Startup Phase        |        vSpring Container Initialization        |        vBean Creation & Dependency Injection

If anything fails in this chain → Application will NOT start.




3️⃣ Most Important Spring Bean Exceptions




1️⃣ BeanCreationException


📌 Definition


Thrown when Spring fails to create a bean.


📦 Package

org.springframework.beans.factory.BeanCreationException

🚩 Common Causes


- Constructor failure

- Exception inside @PostConstruct

- Invalid configuration

- Missing dependencies

- Circular dependencies




❌ Example


@Componentpublic class UserService {    public UserService() {        throw new RuntimeException("Failed during bean creation");    }}

🔥 Error


BeanCreationException: Error creating bean with name 'userService'



✅ Real-World Scenario


- Database connection failure

- Invalid property value

- Misconfigured bean




2️⃣ NoSuchBeanDefinitionException


📌 Definition


Thrown when Spring cannot find a required bean in the container.


📦 Package

org.springframework.beans.factory.NoSuchBeanDefinitionException



❌ Example


@Servicepublic class OrderService {    @Autowired    private PaymentService paymentService; // No bean defined!}

If `PaymentService` is not annotated with `@Component`, `@Service`, or defined in config.


🔥 Error


NoSuchBeanDefinitionException: No qualifying bean of type 'PaymentService'



✅ Fix


✔ Add annotation:


@Servicepublic class PaymentService {}

✔ Or define bean manually:


@Configurationpublic class AppConfig {    @Bean    public PaymentService paymentService() {        return new PaymentService();    }}



3️⃣ NoUniqueBeanDefinitionException


📌 Definition


Thrown when multiple beans of the same type exist and Spring doesn't know which one to inject.




❌ Example


@Servicepublic class PayPalService implements PaymentService {}@Servicepublic class StripeService implements PaymentService {}

@Autowiredprivate PaymentService paymentService;

🔥 Error


NoUniqueBeanDefinitionException: expected single matching bean but found 2



✅ Fix Option 1 – @Primary


@Service@Primarypublic class PayPalService implements PaymentService {}



✅ Fix Option 2 – @Qualifier


@Autowired@Qualifier("stripeService")private PaymentService paymentService;



4️⃣ BeanCurrentlyInCreationException


📌 Definition


Occurs due to circular dependencies.




🔁 Circular Dependency Example


@Componentpublic class A {    @Autowired    private B b;}

@Componentpublic class B {    @Autowired    private A a;}

🔥 Error


BeanCurrentlyInCreationException



📊 Circular Dependency Diagram


Bean A ---> depends on ---> Bean B   ^                          |   |                          v   <------- depends on --------



✅ Solutions


✔ Use constructor injection carefully

✔ Break circular dependency

✔ Use `@Lazy`


@Autowired@Lazyprivate B b;



5️⃣ UnsatisfiedDependencyException


📌 Definition


Thrown when Spring cannot satisfy a dependency required by a bean.




❌ Example


@Servicepublic class UserService {    private final PaymentService paymentService;    public UserService(PaymentService paymentService) {        this.paymentService = paymentService;    }}

If `PaymentService` bean is missing.


🔥 Error


UnsatisfiedDependencyException



6️⃣ BeanInitializationException


📌 Definition


Occurs when initialization logic fails (like @PostConstruct).




❌ Example


@Componentpublic class DataLoader {    @PostConstruct    public void init() {        throw new RuntimeException("Init failed");    }}



4️⃣ Exception Hierarchy (Important for Interviews)


BeansException   |   ├── BeanCreationException   |      ├── BeanCurrentlyInCreationException   |      └── UnsatisfiedDependencyException   |   ├── NoSuchBeanDefinitionException   |      └── NoUniqueBeanDefinitionException   |   └── BeanInitializationException



5️⃣ Quick Comparison Table


ExceptionCauseWhen It Happens------------------------------------BeanCreationExceptionBean instantiation failsDuring bean creationNoSuchBeanDefinitionExceptionBean not foundDuring injectionNoUniqueBeanDefinitionExceptionMultiple beans foundDuring injectionBeanCurrentlyInCreationExceptionCircular dependencyDuring context loadingUnsatisfiedDependencyExceptionMissing dependencyDuring wiringBeanInitializationExceptionInit method failsAfter creation


6️⃣ How to Debug Bean Exceptions




🔎 Step 1 – Read Bottom of Stack Trace


Always scroll to the **root cause**:


Caused by: java.lang.NullPointerException



🔎 Step 2 – Enable Debug Logs


debug=true



🔎 Step 3 – Use Spring Boot Actuator


Add dependency:


<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-actuator</artifactId></dependency>

Endpoint:

/actuator/beans



7️⃣ Best Practices to Avoid Bean Exceptions


✔ Prefer constructor injection

✔ Avoid field injection

✔ Avoid circular dependencies

✔ Use @Qualifier when multiple beans exist

✔ Keep configuration clean

✔ Use @Primary wisely

✔ Validate properties using @ConfigurationProperties




8️⃣ Real Interview Questions


1. Difference between `NoSuchBeanDefinitionException` and `NoUniqueBeanDefinitionException`?

2. How does Spring resolve circular dependencies?

3. Why is constructor injection preferred?

4. What causes BeanCreationException?

5. How to debug Spring startup failure?




9️⃣ Final Summary


Spring Bean exceptions mainly occur due to:


- Missing beans

- Multiple beans

- Circular dependencies

- Configuration errors

- Initialization failures


Mastering these helps you:


- Debug faster

- Build production-ready apps

- Crack Spring Boot interviews

- Handle real-world enterprise issues