Question

I have a service interface UserService and an implementing class UserServiceImpl. When I try to inject UserServiceImpl to a variable in a controller class, it throws an NoSuchBeanDefinitionException. But when I inject UserService interface, it works fine.

The interface UserService is annotated with @Service. The implementing class doesn't have any annotation as such.

Confused why this is happening?

Was it helpful?

Solution

The implementation should have the annotation. Not the interface. And the controller should depend on the interface, not on the implementation. That's what would allow Spring to inject an AOP proxy, allowing for transactions, security, etc:

public interface UserService {
    ...
}

@Service
public class UserServiceImpl implements UserService {
    ...
}


@Controller
public class UserController {
    @Inject
    private UserService userService;

    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top