栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring中AOP操作---AspectJ注解相关程序说明

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring中AOP操作---AspectJ注解相关程序说明

//第一步:创建类,在类里面定义方法
//被增强类
@Component
public class User {
    public void add(){
        System.out.println("add................");
    }
}
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import  org.aspectj.lang.ProceedingJoinPoint;
//第二步:创建增强类,编写增强逻辑
//在增强类里面,创建方法,让不同方法代表不同的通知类型
//增强的类
@Component @Aspect
//加一个Aspect注解  代表着生成一个代理对象
public class UserProxy {
    @Pointcut(value="execution(* com.company.Spring5.AOP.aopAnnotation.User.add(..))")
    public void pointCut(){
//        相同的切入点的抽取
    }

//    在增强类里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

    //    前置通知
//    @Before(value="execution(* com.company.Spring5.AOP.aopAnnotation.User.add(..))")  因为我们对相同的切入点进行提取了,便不再一个一个的写execution表达式了
    @Before(value="pointCut()")
    public void before(){
        System.out.println("before......................");
    }
    //    后置通知
    @AfterReturning(value="pointCut()")
    public void afterReturning(){
        System.out.println("afterReturning......................");
    }
    //    环绕通知
    @Around(value="pointCut()")
    public void around(ProceedingJoinPoint proceedingJoinPoint){
        System.out.println("around前......................");
//        被增强的方法执行,就是这么调用
        try {
            proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("around后......................");
    }
    //    异常通知
    @AfterThrowing(value="pointCut()")
    public void afterThrowing(){
        System.out.println(" afterThrowing......................");
    }
    //    最终通知
    @After(value="pointCut()")
    public void after(){
        System.out.println("after......................");
    }
}




    

    

    

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    @org.junit.Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean11Proxy.xml");
//        这个地方的id user 是使用的注解的方式,只有在getBean的时候,这个对象才会创建
//        执行的是被增强类的方法,看看被增强之后有什么变化
        User user = context.getBean("user",User.class);
//        在add方法之前,会执行增强的before方法
        user.add();
    }
}

 测试结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号