why are interfaces recommended for spring beans?

Viewed 3621

I'm learning Spring and ran into this design question. I'm not sure how to interpretate it. Should I always use an interface instead of just pointing to the actual implementation when linking beans? I imagine it becomes easier to test from a mocking perspective but should I follow it dogmatically? ie a bean should always refer the interface of another bean.

Example:

Class Car{
    @Autowired
    private IEngine engine;
}

Class Engine{}

Interface IEngine{}

vs

Class Car{
    @Autowired
    private Engine engine;
}

Class Engine{}
3 Answers

Well, it is kind of Spring conceptors love the concept of interfaces. The nominal use case is to define a bean as a concrete class and use it through an interface. You can use a bean with its concrete class, and it will work for the vast majority of use cases, but it will sometimes lead to a more complex implementation.

An example is the way you use a database. The (business layer) classes reading from or writing to the database should only use an interface. That way you can change to a different database without changing a single character in the business class. That can be generalized to any kind of refactoring: Spring with interfaces allows you to change a bean implementation without changing anything in its callers.

Another example is Spring AOP. If you use interfaces, it leads to a piece of cake because JDK proxies are enough. If you want to use concrete classes, you have to use a patcher to modify the class at load or run time. Which may require an agent...

Long story made short, you can use concrete classes if you want, but Spring usage will be smoother is you use interfaces.

Many reasons:

  1. You will be having room to extends some other class where it implements

  2. There can be many implementation for one bean itself . check @Primary annotation. You will get more idea

More over it is simple abstraction which is a very nice feature of java.

No one stops you from using concrete class instead of interface, spring will works the same way we use interface.

An important point to remember is that Spring wants to be able to decorate your bean when needed, in a way that is transparent to your application. If you define beans implementing interfaces, and then reference them via interfaces, the Spring can create bean implementations as wrappers around your class, still implementing your interface, and your code won't be affected. The default implementation Spring uses is based on this idea.

Spring can also implement your beans by extending your class, or by manipulating the bytecode for your class at load time - in which case a POJO class is all you really have to have. But configuring these alternative approaches is more complicated.

Related