Use of proxies in Spring AOP Use of proxies in Spring AOP spring spring

Use of proxies in Spring AOP


Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxies for your target objects.

According to Spring documentation, in case your target implements at least one interface, a JDK dynamic proxy will be used. However if your target object does not implement any interfaces then a CGLIB proxy will be created.

This is how you can force creation of the CGLIB proxies (set proxy-target-class="true"):

 <aop:config proxy-target-class="true">    <!-- other beans defined here... --> </aop:config>

When using AspectJ and its autopoxy support you can also force CGLIB proxies. This is where the <aop:aspectj-autoproxy> is used and also here the "proxy-target-class" must be set to true:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Please refer to Proxying mechanisms section of Aspect Oriented Programming with Spring documentation for more details.


Spring prefers to use interfaces for AOP because it can use JDK proxies.

Say for example I have an interface MyService

public interface MyService {    void doSomething();}

And an implementation MyServiceImpl

@Servicepublic class MyServiceImpl implements MyService {    public void doSomething() {        // does something!    }}

If Spring discovers that you've configured aspects for MyService, it will create a JDK Proxy that implements MyService and then proxy all calls through to your MyServiceImpl bean, adding aspect functionality where appropriate.

JDK proxies work by implementing the same interface as your target object and delegating calls to it; they do not work if there is no interface to implement. In case you don't have an interface like above, Spring needs to use a byte code library like CGLIB to dynamically create classes at runtime that incorporate the aspect functionality.


I found a blog here that clearly explains how AOP,Caching & Transaction works using runtime proxy classes.

When not coding to interface (quoting from the blog's section 'What if the bean class does not implement any interface?'):-

By default, if your bean does not implement an interface, Spring uses technical inheritance: at startup time, a new class is created. It inherits from your bean class and adds behavior in the child methods. In order to generate such proxies, Spring uses a third party library called cglib.