Spring AOP AspectJ 切面编程

Spring AOP AspectJ 切面编程

Student类

package com.ann.pojo;

public class Student implements MyInterface {
    @Override
    public void testMethod() {
        int i = 6/0;  // 异常通知
        System.out.println("好好学习,天天向上!Go!Go!Go!");
    }
}

Advice类

package com.ann.advice;

import org.aspectj.lang.ProceedingJoinPoint;

public class MyAdvice {
    // 前置通知
    public void beforce(){
        System.out.println("前置通知我最前~");
    }
    // 后置通知
    public void after(){
        System.out.println("后置通知我最后~");
    }
    // 环绕通知
    public Object myRound(ProceedingJoinPoint pjp) throws Throwable {
        // 环绕前
        System.out.println("环绕前");
        // 放行
        Object proceed = pjp.proceed();
        // 环绕后
        System.out.println("环绕后");

        return proceed;
    }
    // 异常通知
    public void myThrow(Exception e){
        System.out.println("xxxxxx异x常x通x知xxxxxx:"+e.getMessage());
    }
}

applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!--配置业务类bean-->
    <bean id="stu" class="com.ann.pojo.Student"></bean>
    <!--配置通知类bean-->
    <bean id="adv" class="com.ann.advice.MyAdvice"></bean>
    <!--配置aop-->
    <aop:config>
        <aop:aspect ref="adv">
            <!--配置切点-->
            <aop:pointcut id="pc" expression="execution(* com.ann.pojo.Student.testMethod())"/>
            <aop:before method="beforce" pointcut-ref="pc"></aop:before>
            <!--aop:after不包含在try语句中,所以报错依然会执行。aop:after-returning是包含在try语句中。-->
            <aop:after method="after" pointcut-ref="pc"></aop:after>
            <aop:around method="myRound" pointcut-ref="pc"></aop:around>
            <aop:after-throwing  method="myThrow" pointcut-ref="pc" throwing="e"></aop:after-throwing>
        </aop:aspect>
    </aop:config>

</beans>

测试代码

package com.ann.test;

import com.ann.pojo.MyInterface;
import com.ann.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AspectTest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        MyInterface stu = (MyInterface) ac.getBean("stu");
        stu.testMethod();

    }
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值