Spring AOP for non spring component

Spring AOP can only be applied to Spring-managed components/beans, not to non-Spring POJOs. If you want to apply AOP to non-Spring classes you need AspectJ, not a proxy-based “AOP lite” framework like Spring AOP. For more information about how to use AspectJ (which does not need Spring at all) in combination with Spring and how … Read more

Spring: register advice programmatically at runtime

The previous solution is too invasive as it not only creates advice on the fly but also handles advising beans. This replicates functionality of Spring’s AbstractAdvisorAutoProxyCreator, specifically the getAdvicesAndAdvisorsForBean method, where Spring will locate and apply eligible Advisors to each bean. A better approach is to simply programmatically create Advisors and let Spring handle the … Read more

Self-invocation behaviour in @Configuration vs. @Component classes

Regular Spring @Components For an explanation of how normal Spring (AOP) proxies or dynamic proxies (JDK, CGLIB) in general work, see my other answer with illustrative sample code. Read that first and you will understand why self-invocation cannot be intercepted for these types of proxies via Spring AOP. @Configuration classes As for @Configuration classes, they … Read more

How to instrument / advice a Spring Data (JPA) repository?

Although the OP heavily relied on AspectJ solutions, the question as it stands doesn’t directly suggest that solutions should be limited to AspectJ. Therefore I’d like to offer a non-AspectJ way to advise a Spring Data JPA Repository. It is based upon adding a custom Interceptor into barebone Spring AOP proxy interceptor chain. First, configure … Read more

Error creating bean with name ‘org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0’ defined in ServletContext resource

This is a limitation in Spring AOP. When you use AspectJ pointcuts to weave aspects into beans, Spring will use CGLIB to generate a subclass of the target, and invoke the aspects from that subclass. If the target class does not have a public default constructor, however, this will fail. CGLIB does have the ability … Read more