I’ve started to use Spring recently. And I’m making spring mvc project. So my question is if it’s preferred to make interfaces and autowire it with particular implementation by spring or just use class instances
in case when I have only one implementation of that interface?
For example:
@Controller
public class MyController {
@Autowired
MyService myService;
@RequestMap("/")
public String mainPage() {
...
}
}
or
@Controller
public class MyController {
@RequestMap("/")
public String mainPage() {
MyService myService = new MyServiceImpl();
...
}
}
if there is only one implementation of MyService interface?
In most cases you should go with injection because:
MyServiceImplas well because it manages this objectEven if your service does not have an interface, because of the second reason you should consider injection.
The only case when you might want to skip Spring is when the class does not have any dependencies and is stateless. But most likely such a class is a utility that does not need any an instance at all because it has only
staticmembers.