Code architecture of service interface and service impl classes spring

When you use the annotation @Autowired, Spring will automatically search in its application context a candidate to be injected in the controller. A valid candidate should be a concrete class marked as a Spring bean, using annotation @Service for example.


This is basically how Spring works:

The service implementation should be a Spring bean (it either has to have a @Component or @Service annotation, or should be defined in a Spring XML configuration file), so that Spring will find it and register it in the Spring application context.

Then you use dependency injection, through the @Autowired annotation, to inject the implementation of the service into the controller. This means that Spring will look at your controller, it will find the @Autowired annotation on the service member variable and initialize it with a bean that it finds in the application context, which will be the instance of the service implementation class that it has registered earlier. So, after Spring is done, service will refer to the instance of ServiceImpl.

See the Spring Framework reference documentation for information on how dependency injection works with Spring: The IoC container


Basic idea behind having this kind of architecture is little different than just spring convention.

Lets say tomorrow you decide, you dont want to have single application for both projects, and go into one deployment for webapp and another for service Example UserService WebApp

so for WebApp to connect to UserService it will have to make http requests to get any kind of data. then you will have to change all your WebApp code to make it compatible to new changes. For example instead directly calling method of Service you will call httpClient. To avoid this rework what you can do is, Using interface Service you implement your own ServiceImpl and make all http request in there, rest remains intact.

Similar stuff will be done in UserService, it will have its own ServiceImpl as before but will be called in Controller as a singleton object.

Your answer : You can refer to ServiceImpl directly, it will serve the purpose, difference is only when ServiceImpl is not part of current module or any dependency, but final bundled project will have its implementation through some sibling module probably