zhazi
2021-01-03 15:15:39 +08:00
Should we use interfaces with our Service Beans?
Short answer: No.
If you want the long answer, here it is:
One of the main interests of using Spring is AOP. This is the technology that allows Spring to add new behaviors on top of your Beans: for instance, this is how transactions or security work.
In order to add those behaviors, Spring needs to create a proxy on your class, and there are two ways of creating a proxy:
If your class uses an interface, Spring will use a standard mechanism provided by Java to create a dynamic proxy.
If your class doesn’t use an interface, Spring will use CGLIB to generate a new class on the fly: this is not a standard Java mechanism, but it works as well as the standard mechanism.
Some people will also argue that interfaces are better for writing tests, but we believe we shouldn’t modify our production code for tests, and that all the new mocking frameworks (like EasyMock) allow you to create very good unit tests without any interfaces.
So, in the end, we find that interfaces for your Service beans are mostly useless, and that’s why we don’t recommend them (but we leave you with the option to generate them!).