When using my aop cache framework, I sometimes saw that methods were not cached although they should. Some further investigation revealed that this only happened when the method was invoked inside the target object itself.
So if you have an object PersonDAO and you invoke PersonDAO#getPerson() on it from another object, the method is proxied. But if you have a method PersonDAO#getAllPersons() and from there you call this.getPerson(), the method will not be proxied. This is described here in more detail.
The solution I implemented was adding a getThis() method to the affected classes. Not pretty, but it works…
/** * When running in an AOP proxy, methods that are called inside the proxy * are invoked on the target itself, instead of on the aop proxy. The workaround for * this is to ask the AopContext for the current proxy and invoke the method there. * * See http://opensource.atlassian.com/projects/spring/browse/SPR-2226. * * @return the AOP proxy for this object */ private PersonDAO getThis() { try { return (PersonDAO) AopContext.currentProxy(); } catch (AspectException exc) { logger.error("Not running inside an AOP proxy, so no proxy can be returned: " + exc.getMessage()); return this; } }
The only thing left to do was to expose the proxy in the proxyCreator, which is not enabled by default. I did this with BeanNameAutoProxyCreator#setExposeProxy(true).