JAVA_CAT
JAVA_CAT

Reputation: 859

Autowiring of Service and Service Implementation class

Following are my code

@RestController
public class EmployeeController {

    @Autowired
    EmployeeService empService;

public EmployeeController (EmployeeService Impl empServiceImpl) {
        super();
        this.empService = empServiceImpl;

    }

}

@Service
public interface EmployeeService {

public List<EmployeeDTO> getAllEmployeeDetails()

}

public class EmployeeServiceImpl {

public List<EmployeeDTO> getAllEmployeeDetails(){
  //methods business logic and repo call goes here
}

}

When I start my server I am getting below error.

Parameter 1 of constructor in com.app.in.controller.EmployeeController required a bean of type 'com.app.in.service.EmployeeServiceImpl' that could not be found

My understanding might be wrong. If I annotate the EmployeeSeriveImpl class also with @Service then it working.Is that is the correct way to do it ? My question is the service interface is annotated with @Service still why its implementation is also required to annotation. Please let me know if I miss something in that ? What is the standard method to solve this issue ?

Upvotes: 0

Views: 1716

Answers (1)

ikos23
ikos23

Reputation: 5354

You can get your dependency injected using a constructor. And @Autowired is optional in this case.

This is your example, but with a few corrections:

@RestController
public class EmployeeController {

    // private final is a good practice. no need in @Autowire
    private final EmployeeService empService;

    // this constructor will be used to inject your dependency
    // @Autowired is optional in this case, but you can put it here
    public EmployeeController (EmployeeService empServiceImpl) {
        this.empService = empServiceImpl;

    }

}

I assume you have an interface EmployeeService and class EmployeeServiceImpl which implements that interface and is Spring Bean.

Something like this:

@Service
public class EmployeeServiceImpl implements EmployeeService {}

Why this @Service is needed? When you put this annotation on your class, Spring knows this is a bean that Spring should manage for you (container will create an instance of it and inject it wherever it is needed).

Check Spring docs to get more details about Dependency Injection.

The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null.

Upvotes: 1

Related Questions