程序员社区

【Spring学习及总结18】AOP的使用步骤

  1. 导包:
    在这里插入图片描述

导入后发现:导入上面的jar包没用,因此重新导入这个jar包

 <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
	 <groupId>org.aspectj</groupId>
	 <artifactId>aspectjweaver</artifactId>
	 <version>1.9.4</version>
</dependency>
  1. 写配置文件:
    1.将目标类和切面类(封装了通知方法(在目标方法执行前后执行的方法))加入到IOC容器中。
    2.应该告诉Spring到底哪个类是切面类:@Aspect
    3.告诉Spring,切面类里面的方法都是何时何地运行的
     @Before:在目标方法执行之前执行(前置通知)
     @After:在目标方法执行之后执行(后置通知)
     @AfterThrowing:在目标方法抛出异常以后执行(异常通知)
     @AfterReturning:在目标方法正常返回之后执行(返回通知)
     @Around:环绕通知

编写目标类:

@Component
public class MyMath implements Caculator {
    public int add(int i, int j) {

        return i+j;
    }

    public int sub(int i, int j) {
        return i-j;
    }

    public int mul(int i, int j) {
        return i*j;
    }

    public int div(int i, int j) {
        return i/j;
    }
}

编写日志类(切面类):

@Aspect
@Component
public class LogUtils {
    //在目标方法执行之前执行
    //exception(访问权限符 返回值类型 方法签名)
    @Before("execution(public int com.hh.pojo.MyMath.*(int,int))")
    public static void logStart(){
        System.out.println("【xxx】方法开始执行,用的参数列表【xxx】");
    }

    //在目标方法执行之后执行
    @AfterReturning("execution(public int com.hh.pojo.MyMath.*(int,int))")
    public static void logReturn(){
        System.out.println("【xxx】方法正常执行完成,计算结果是:");
    }

    //在目标方法出现异常时执行
    @AfterThrowing("execution(public int com.hh.pojo.MyMath.*(int,int))")
    public static void logException(){
        System.out.println("【xxx】方法执行出现异常了,异常信息是:这个异常通知");
    }

    //在目标方法结束的时候执行
    @After("execution(public int com.hh.pojo.MyMath.*(int,int))")
    public static void logEnd(){
        System.out.println("【xxx】方法最终结束了");
    }
}

配置spring.xml文件:

<context:component-scan base-package="com.hh"/>
<!--开启基于注解的AOP功能-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

测试类:

public class MyTest {
    ApplicationContext context =
            new ClassPathXmlApplicationContext("spring.xml");
    @Test
    public void test(){
        Caculator bean = context.getBean(Caculator.class);
        bean.add(1,2);
    }
}

在这里插入图片描述

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 【Spring学习及总结18】AOP的使用步骤

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区