Aspect Oriented Programming
https://www.youtube.com/watch?v=x2f4NzNCkCI
Cross Cutting Concerns => Moving non-business logic outside of Business logic like transactions, logging, security, ...
Aspect classes => Hold non-business logic
Business Classes will be binded with Aspect classes
*****************************************************************
Terminologies:
-
Aspect - Class - Like transactions, logging, security, ...
-
Advice - Aspect Class methods and must be any one of the following:
- Before Advice - Before running business method
- After Advice - After running business method
- Around Advice - 2 Parts. Order of execution:
- First part
- Before advice
- Business method
- Second part
- After returning Advice - Only runs with successful business method response
- After throwing Advice - Only runs with failed business method response
-
Pointcut - It is an expression and defines business method who seeks advice
- Example:
@Pointcut("execution(public * com.bhaskarmantrala.hub.springbootfoundation.*(..))") public void pointCutMethod() {}
-
JoinPoint - Specifies / Binds what advice is required by business method
- Example:
import org.aspectj.lang.annotation.Before; @Pointcut("execution(public * com.bhaskarmantrala.hub.springbootfoundation.*(..))") public void pointCutMethod() {} @Before("pointCutMethod()") public void adviceMethod() {}
- Example:
-
Target - Business class object
-
Weaving - Creates a new Proxy class consists of both business logic code and aspect logic together @EnableAspectJAutoProxy Configuration file
@Configuration
@ComponentScan(basePackages = {"com.bhaskarmantrala.hub.springbootaop.core",
"com.bhaskarmantrala.hub.springbootaop.advice"})
@EnableAspectJAutoProxy
- Proxy - JDK Dynamic Proxy - Class object with both business logic + aspect logic
*****************************************************************
Spring AOP using AspectJ using Annotations
Add a dependency - Spring Boot Starter AOP
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.5.12</version>
</dependency>```