NOTE

2.30 使用

1. 创建项目 2. pom.xml 3. 代码 3.1. 业务逻辑类 - HelloWorld 3.2. 切面类 3.3. 配置类

Java创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 创建项目

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.zsk</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. 代码

3.1. 业务逻辑类

  • HelloWorld
public class Calc
{
    public int div(int a, int b)
    {
        System.out.println(a / b);
        return a /  b;
    }

}

3.2. 切面类

@Aspect//表示切面类
public class LogAspects
{
    //切入点。需要代理的目标方法
    @Pointcut("execution(public int com.zsk.test.aop.Calc.*(..))")
    public void pointCut()
    {
    }

    //前置通知:目标方法运行之前
    @Before("pointCut()")
    public void logStart(JoinPoint joinPoint)
    {
        System.out.println("logStart: parameters:"+ Arrays.asList(joinPoint.getArgs()));
    }

    //后置通知:目标方法运行之后
    @After("pointCut()")
    public void logEnd(JoinPoint joinPoint)
    {
        System.out.println("logEnd: methodName:" + joinPoint.getSignature().getName());
    }


    //返回通知:目标方法正常返回之后
    @AfterReturning(value = "pointCut()", returning = "result")
    public void logReturn(Object result)
    {
        System.out.println("logReturn: result:" + result);
    }

    //异常通知:目标方法运行出现异常
    @AfterThrowing(value = "pointCut()", throwing = "exception")
    public void logException(Exception exception)
    {
        System.out.println("logException: exceptino:" + exception.getMessage());
    }

    //环绕通知:jointPoint.proceed().手动调用目标方法
}

3.3. 配置类

@EnableAspectJAutoProxy//开启spring aop
@Configuration
public class AopConfig
{
	//把切面和业务逻辑都加入spring容器
    @Bean
    public Calc calc()
    {
        return new Calc();
    }

    @Bean
    public LogAspects logAspects()
    {
        return new LogAspects();
    }

    public static void main(String[] args)
    {
    	//需要从spring 容器中获取
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopConfig.class);
        Calc calc = applicationContext.getBean(Calc.class);
        calc.div(10,10);
        System.out.println("==================");
        calc.div(10,0);

    }
}