Unsatisfied dependency expressed through field – nested exception is NoSuchBeanDefinitionException

In Spring Boot Compilation, this might be one of the most common errors we would have faced, Full Error Trace is

WARN Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ’employeeService’: Unsatisfied dependency expressed through field ‘repository’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.example.repository.EmployeeRepository’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

In the above error, the Compilation unit says that there is a bean name employeeService mentioned in the service package which does not have a proper repository(com.example.repository.EmployeeRepository) linked to it, But if you check the code level, there will be no issue, all you need to focus is in your main application class. That’s where the problem happened.

Description:

Field repository in com.example.service.EmployeeService required a bean of type 'com.example.repository.EmployeeRepository' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

The Compilation Unit provides a Recommendation as follows.

Action:

Consider defining a bean of type ‘com.example.repository.EmployeeRepository’ in your configuration.

It means EmployeeRepository is out of our configuration, so how do we get through it.

Solution :

Our main class is located in

package com.example.springboot;

Our Service class is located in

package com.example.service

So here the component scan across the class will take place when the compilation unit invokes through the annotation @SpringBootApplication. It scans all the classes under the package com.example.springboot, because the main class is located in the package and scans all the sub-packages of the com.example.springboot and leaving the other packages such as com.example.service and repository class, hence it has no idea what the Service Class about and throw the error as

Error creating bean with name 'employeeService': Unsatisfied dependency expressed through field 'repository'

To make it perfect you need to define the Main class applicable for all the classes so that it can see all the classes in the application. To restructure the main class in the common path such as below

From : package com.example.springboot
To : package com.example

The structure will look as follows,

spring boot exception

Now Compile the unit, It should work.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *