Question

I don't know the meaning of using proxy in spring. what is efficient?

Was it helpful?

Solution

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.)

OTHER TIPS

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.

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".
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top