When we annotate a class as @Autowired, does it HAVE to be a interface or can it be a class?
All the examples of using Spring I have seen, use an interface and then implement it on a class. The interface type is then used to call a function on the Concrete class. Can we not just simply add @Autowired to a concrete class rather than an interface.
I know of the Programme to a interface analogy in JAVA, but if u are not depending on Polymorphism, then why to write an interface?
No, you don't have to use interfaces, this is completely fine as far as Spring is concerned:
@Service
public class FooService {
@Autowired
private FooDao fooDao;
}
or you can even go for construction injection:
@Service
public class FooService {
private final FooDao fooDao;
public FooService(FooDao fooDao) {
this.fooDao = fooDao;
}
}
Often interfaces are anachronic practice repeated by every subsequent generation. Don't use them if they are not required. And they aren't required if they will always have just one implementation or if you want to mock such a class (modern mocking frameworks mock classes without any problem).
There is also nothing wrong in injecting concrete classes, like FooDao in example above. It has some technical implications wrt. proxying, but nothing that can't be comprehended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With