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

关于spring5中使用aspect注解的demo

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

关于spring5中使用aspect注解的demo

 学习spring5的时候,看的某谷视频P30,发现一使用@Aspect注解就开始报错BeanCreationException,然而网上给出的解决方法都是:aspectj的三个包(rt、appliance、weavers)导入一下最新版本的,尝试过后并没有解决。发现报错的位置是spring包下。由此发现自己导包的时候,将一部分包导的是课程使用的,另一部分包导入的是网上下载的,这样spring版本自己都不兼容吧。改了之后就对了。

郁闷了一晚上。以此告诫后来者。

package ....aopAnno;
import org.springframework.stereotype.Component;


//1 创建被增强的类,定义方法

//4 使用注解创建User和UserProxy对象
//被增强的类
@Component (value = "user")
public class User {
    public void add() {
        System.out.println("User add...");
    }
}



package ....aopAnno;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;


//2 创建增强类,编写增强逻辑
//4 增强的类
@Component (value = "userProxy")
@Aspect //生成代理对象
public class UserProxy {
    //相同切入点抽取
    @Pointcut(value = "execution(* ...aopAnno.User.add(..))")
    public void pointDemo(){
    }

    //6 前置通知,@Before注解表示作为前置通知,方法前执行
    // @Before(value = "execution(* ...aopAnno.User.add(..))")
    @Before(value = "pointDemo())")
    public void before() {
        System.out.println("UserProxy before...");
    }
    //6 后置通知(返回通知),方法后执行,出现异常不执行
    @AfterReturning(value = "execution(* ...aopAnno.User.add(..))")
    public void afterReturning() {
        System.out.println("UserProxy afterReturning...");
    }

    //6 最终通知,方法后执行,出现异常也执行
    @After(value = "execution(* ...aopAnno.User.add(..))")
    public void after() {
        System.out.println("UserProxy after...");
    }

    //6 异常通知,出现异常才执行
    @AfterThrowing(value = "execution(* ...aopAnno.User.add(..))")
    public void afterThrowing() {
        System.out.println("UserProxy afterThrowing...");
    }

    //6 环绕通知, 在方法前后都执行
    @Around(value = "execution(* ...aopAnno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("UserProxy around before...");
        proceedingJoinPoint.proceed();
        System.out.println("UserProxy around after...");
    }
}

public class TestAopAnno {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("proxyAnnoBean.xml");
        User user = context.getBean("user", User.class);
        user.add();
        
    }

}
配置文件:




    
    
    
    

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

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

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