SpringMVC Basics--Using @Autowired to inject bean objects in Controller Why inject interfaces instead of injecting implementation classes

In the Controller layer, use @Autowired to inject the TestService interface.
insert image description here
What we inject is the service layer interface, as follows
insert image description here
instead of the service layer implementation class
insert image description here

Why?

The principle of AOP is dynamic proxy. There are two types of proxy that can be used. One is the dynamic proxy based on JDK, which is based on the implementation class, and the other is the dynamic proxy based on Cglib, which is based on subclasses. JAVA dynamic proxy .

We are using a JDK-based dynamic proxy. If we inject TestServiceImpl instead of TestService in the Controller, then transaction AOP cannot be used, that is to say, there is no transaction control. Why? We know that Spring is configured with AOP and transaction control, so transaction control can be completely managed by spring. The following are all methods in serviceImpl configured by the
configured entry point expression , but Impl is the target object, the real proxy
insert image description here
The object is the interface he implements, and the transaction control is only available in the proxy object, but not in the target object.

Guess you like

Origin blog.csdn.net/qq_44660367/article/details/110261431
Recommended