- Add dependencies:
- Create Spring AOP Java configuaration class with @Configuration, @EnableAspectJAutoProxy, @ComponentScan [JavaConfig].
- Create bean class with @Component [Account].
- Create Main app class
[LoggingApp]
- Read Spring config Java class to get the context
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
- Get bean class from Spring container
BeanClass aBean = context.getBean("aBean", BeanClass.class);
- Call business methods of the bean
- Close the context:
context.close();
- Create Aspect class with @Aspect and @Component (to group related Advices)
[LoggingAspect]
- Setup logger [java.util.logging.Logger] or use @Logger from Lombok (to log Advices output in the same thread? as Spring)
- Setup Pointcut declarations with @Pointcut (to associate business methods of bean with Advices)
- Create Advices (to execute whatever code with associated business methods)
- @EnableAspectJAutoProxy
- AnnotationConfigApplicationContext
- Aspect with @Aspect
- Advice
[LoggingAspect]
- @Before: run before the method
- @AfterReturning: run after the method (success execution), use
returning
to get returning result - @AfterThrowing: run after the method (if exception thrown), use
throwing
andThrowable
the capture the exception, can not handle exception - @After: run after the method (regardless of outcome)
- @Around: run before and after the method, use
ProceedingJoinPoint.proceed()
to execute target method when desired, can handle/rethrow exception usingtry catch
block
- Pointcut expression:
execution(return_type package.class.method(params))
- Wildcards
[LoggingAspect]
- (): no args
- (*): one arg, any types
- (..): zero or more args, any types
- (fully qualified classname)
- Declare with @Pointcut [CommonAspect]
- Combine pointcut expressions using &&, ||, ! [CommonAspect]
- Wildcards
[LoggingAspect]
- @Order: Decide the execution order of all Advices in a Aspect
- Lower numbers have higher predence
- Negative numbers are allowed
- Does not have to be consecutive
- JoinPoint: contains metadata of the business method
[TestingAspect]
- Get method signature by
MethodSignature
andJoinPoint.getSignature()
- Get method parameters by
Objec[]
andJoinPoint.getArgs()
- Get method signature by
- 📌 Quick copy fully qualified classname from that class
- 📌 Group related advices into one Aspect to order with @Order (i.e., logging aspect, testing aspect)
- 📌 Declare public pointcut expressions in a common Aspect to share with other Aspects [CommonAspect].
- ℹ️ Order execution: @Before -> @Around (before) -> Business method -> @Around (after) -> @After -> @AfterThrowing