I can't understand the difference between the annotation over the interface and the implementation. I've searched a lot of information it's not complete and it doesn't seem right to me. I decided to look into the question.
Consider
1 Variant.
Interface
@Service
public interface AuthenticationService {
boolean authenticate(String username, String password);
}
Impl
public class InMemoryAuthenticationService implements AuthenticationService {
@Override
public boolean authenticate(String username, String password) {
//...
}
}
And
@Autowired
private AuthenticationService authService;
Many sources, including stackoverflow, say that there are 2 key problems with this approach
- We create an unnecessary link to an external library (what library???)
- We may encounter NoSuchBeanDefinitionException (but for some reason there is no mention of @Qualifier or @Primary annotations or other ways)
2 Option
Interface
public interface AuthenticationService {
boolean authenticate(String username, String password);
}
Impl
@Service
public class InMemoryAuthenticationService implements AuthenticationService {
@Override
public boolean authenticate(String username, String password) {
//...
}
}
And
@Autowired
private InMemoryAuthenticationService authService;
In my practice, I always created an interface for the service and injected the interface. But now I've started to see the second option sometimes.
Questions.
Can you describe the pros and cons of both options in more detail? Does it even make sense to use the interfaces then, if they only have 1 implementation?