AOP

Basic information

  • we use Compile-time weaving - it's the most powerful possibility from all aspect-weaving possibilities (e.g. load-time weaving (LTW) doesn't allow to create aspects around private and final methods). Another advantage is that it doesn't have negative performance impact on running application (LTW makes weaving during class initialization). Disadvantage can be that compilation has to be by AspectJ compiler => build script and IDE must be adjust.

    There is blog post about performance comparision: The results are a bit surprising for me for two reasons. First, creating objects marked as @Configurable is less than 4 times slower than creating ordinary objects using new operator.

  • we use JDK dynamic proxies (Dynamic Proxies vs. CGLib proxies)
  • Spring AOP and AspectJ runs in parallel - instances created from Spring factory will be controled by Spring. If classes are created outside of Spring IoC container (classes marked with annotation @Configurable) then AspectJ is used
  • pointcuts syntax = AspectJ syntax

  • all production code (not test code) is compiled by aspectj with use aspectj-maven-plugin, standard compilation with maven-compiler-plugin is disabled (again for production code only)

  • dependency on AspectJ libraries and Spring aspects is necessary (configuration from root pom.xml). We can also add dependency on own custom aspects.

  • Spring Boot configuration spring.aop.auto=true in application.properties is equal to the annotation @EnableAspectJAutoProxy
  • when we want to non-managed classes into Spring IoC container then annotation @EnableSpringConfigured is needed

Creating own aspect

There is module wiseporter-logging (not from OpenHub framework) that contains aspect com.openwise.wiseporter.log.EntitySavingAspect - this aspect logs entity before saving:

where is reference to CommonPointcuts class (module wiseporter-commons):


It's necessary to adjust AspectJ compilation to use this aspect in another modules. We need to add dependency to this module with aspect - see adding wiseporter-logging module into aspectLibraries below.


Common AOP hints

Tips for troubleshooting:

  • enable logging
    • aop.xml: weaver options="-verbose -showWeaveInfo -debug" (valid for LTW only)
    • aspectj-maven-plugin<showWeaveInfo>true</showWeaveInfo> - this option allows to log all changes made by ajc compiler
    • ajc command parameters for setting in IDE: -Xlint:ignore -showWeaveInfo -verbose (ajc params)
    • Spring AOP - log levels configuration

  • exception of the following type "java.lang.IllegalStateException: Post-processor tried to replace bean instance of type [com.openwise.wiseporter.productcatalogue.products.Category] with (proxy) object of type [org.springframework.beans.factory.aspectj.$Proxy70] - not supported for aspect-configured classes!" tells that problem is with ajc compilation