NOTE
Usage
1. Create the project 2. pom.xml 3. Code
This is a historical learning note and may contain outdated or incomplete understanding.
1. Create the Project

2. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring_aop</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.24.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.24.RELEASE</version>
</dependency>
</dependencies>
</project>
3. Code
3.1. Business-Logic Class
- HelloWorld
public class Calc
{
public int div(int a, int b)
{
System.out.println(a / b);
return a / b;
}
}
3.2. Aspect Class
@Aspect// indicates an aspect class
public class LogAspects
{
// Pointcut: the target method that needs to be proxied.
@Pointcut("execution(public int com.example.test.aop.Calc.*(..))")
public void pointCut()
{
}
// Before advice: runs before the target method.
@Before("pointCut()")
public void logStart(JoinPoint joinPoint)
{
System.out.println("logStart: parameters:"+ Arrays.asList(joinPoint.getArgs()));
}
// After advice: runs after the target method.
@After("pointCut()")
public void logEnd(JoinPoint joinPoint)
{
System.out.println("logEnd: methodName:" + joinPoint.getSignature().getName());
}
// Return advice: runs after the target method returns normally.
@AfterReturning(value = "pointCut()", returning = "result")
public void logReturn(Object result)
{
System.out.println("logReturn: result:" + result);
}
// Exception advice: runs when the target method throws an exception.
@AfterThrowing(value = "pointCut()", throwing = "exception")
public void logException(Exception exception)
{
System.out.println("logException: exceptino:" + exception.getMessage());
}
// Around advice: jointPoint.proceed(). Manually invoke the target method.
}
3.3. Configuration Class
@EnableAspectJAutoProxy// enable Spring AOP
@Configuration
public class AopConfig
{
// Add both the aspect and the business logic to the Spring container.
@Bean
public Calc calc()
{
return new Calc();
}
@Bean
public LogAspects logAspects()
{
return new LogAspects();
}
public static void main(String[] args)
{
// Need to obtain it from the Spring container.
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopConfig.class);
Calc calc = applicationContext.getBean(Calc.class);
calc.div(10,10);
System.out.println("==================");
calc.div(10,0);
}
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub