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

spring 5.4 Aop

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

spring 5.4 Aop

aop的实现 1.需要导坐标

      org.aspectj
      aspectjweaver
      1.9.4
    
2.在springConfig配置类中,需要加上注解@EnableAspectJAutoProxy 3.创建一个aop类

在类前面需要添加2个注解:1.@Componen,作用是加入容器的管理2.@Aspect 表示这个类主要是aop。
其中 需要2个注解进行搭配1 注解@Pointcut 注解@Around,@Before 和@After

注解@Pointcut 需要搭配execution和指定包下的接口方法(一般是接口,类也可以实现)。还需要一个private方法,这个方法只是为了连接注解@Around,@Before 和@After,只需要记住名字即可

 @Pointcut("execution(void dao.BookDao.update())")
 private void pt(){}

void:返回值
update:方法名
BookDao:方法所在的类名
dao:类名所在的包
其中可以使用*扫描指定格式的包
void dao.BookDao.up**()代表扫描BookDao类下以up开头的所有方法
void dao.BookDao.date()代表扫描BookDao类下以date结尾的所有方法
void dao
*.update()代表扫描dao包内的所有update方法,也可以结合指定开头和指定结尾
*.dao.BookDao.update()代表扫描所有包内的BookDao下的update方法。

@Before

在注解中绑定@Pointcut注解创建的类名,before指在方法执行前,执行该注解下的方法。

@Before("pt()")
    public void before() {
        System.out.println("before advice ...");
    }

@After
在注解中绑定@Pointcut注解创建的类名,after指在方法执行后,执行该注解下的方法。

@After("pt2()")
    public void after() {
        System.out.println("after advice ...");
    }

@Around(重点)
ProceedingJoinPoint pjp为固定形参,并且返回值固定为Object

@Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("around before advice ...");
        //表示对原始操作的调用
        Integer ret = (Integer) pjp.proceed();
        System.out.println("around after advice ...");
        return ret;
    }

此方法执行后可以看到会先执行proceed前面的输出方法后才会进入before操作。在proceed执行完,就会执行after操作,然后再执行proceed后的输出方法。

around before advice ...
before advice ...
book dao select is running ...
after advice ...
around after advice ...
100
总结

在主程序中,获取bean对象的是接口。
在实现类中,要给类添加注解@Repository,不然会出现获取不到bean对象的错误。

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

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

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