0

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?

4

1 回答 1

1

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;

    ...
}
于 2013-03-30T07:55:35.690 回答