What is the meaning of using proxy ( dynamic proxy) in spring framework?

自古美人都是妖i 提交于 2019-12-02 19:23:19
Thomas Jung

The dynamic proxy is a feature of the JDK. It can be used to implement an interface using an invocation handler.

A dynamic proxy class (simply referred to as a proxy class below) is a class that implements a list of interfaces specified at runtime when the class is created, with behavior as described below. A proxy interface is such an interface that is implemented by a proxy class. A proxy instance is an instance of a proxy class. Each proxy instance has an associated invocation handler object, which implements the interface InvocationHandler.

A dynamic proxy has some overhead. For most use cases the overhead won't be significant, though. The real problem is that the (over)use of dynamic proxies makes an application harder to understand and debug. For example a dynamic proxy will show up with mulitple lines in a stacktrace.

Dynamic proxies are often used to implement decorators. One example of this is AOP in Spring. (I don't want to go into the details of AOP and won't use AOP terminology to keep things simple). Where certain concerns are implemented in one class and used in many places. The dynamic proxies (and invocation handlers) are only the glue code (provided by Spring) to intercept the method calls. (Actually, dynamic proxies are only an implementation detail of this capability. Generating classes on the fly is another possibility to implement it.)

Proxies are used by AOP. In short:

Normally you have.

Caller --> Real object

But when, for example, you want automatic transaction management, spring puts a proxy of your real object

Caller --> Proxy --> Real object

where the proxy starts the transaction.

Here is nice article explaining both the essence of proxies and their efficiency (performance) in spring

We can add a functionality to Java class by modifying the source/byte code or by using subclass or proxy which embeds the additional functionality and delegates the calls to underlying object.

Nilesh

AOP can also use CGLIB proxies. This is used to proxy the classes instead of interfaces.

The other answers are good, but here's how I think of it in very simple terms.

  1. An annotation means "add hidden code for extra behavior."
  2. The framework (or whatever knows what the annotation means) adds bytecode, Spring at runtime, AspectJ at compile time, for example.
  3. It adds code as a proxy along with an interceptor. (A wrapper, decorator, adapter are similar and may be easier to understand than "proxy".)
  4. When the program runs, the interceptor sends execution to the proxy which does its thing, which then may or may not send execution to the class that you coded and that it "wraps".
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!