博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring AOP @Around @Before @After 区别
阅读量:6935 次
发布时间:2019-06-27

本文共 2110 字,大约阅读时间需要 7 分钟。

此段小代码演示了spring aop中@Around @Before @After三个注解的区别@Before是在所拦截方法执行之前执行一段逻辑。@After 是在所拦截方法执行之后执行一段逻辑。@Around是可以同时在所拦截方法的前后执行一段逻辑。

  1. 连接点(JoinPoint) 这个就更好解释了,就是spring允许你是通知(Advice)的地方,那可就真多了,基本每个方法的前、后(两者都有也行),或抛出异常是时都可以是连接点,spring只支持方法连接点。其他如AspectJ还可以让你在构造器或属性注入时都行,不过那不是咱们关注的,只要记住,和方法有关的前前后后都是连接点。
package com.itsoft.action;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.stereotype.Controller;/** *  * @author zxf * 演示aop测试类 */@Controllerpublic class UserAction {    public void queryUsers(){        System.out.println("查询所有用户【all users list】");    }    public static void main(String[] args) {        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-aop.xml");        UserAction userAction = (UserAction)ctx.getBean("userAction");        userAction.queryUsers();        ctx.destroy();    }}
package com.itsoft;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;/** *  * @author Administrator * 通过aop拦截后执行具体操作 */@Aspect@Componentpublic class LogIntercept {    @Pointcut("execution(public * com.itsoft.action..*.*(..))")    public void recordLog(){}    @Before("recordLog()")    public void before() {        this.printLog("已经记录下操作日志@Before 方法执行前");    }    @Around("recordLog()")    public void around(ProceedingJoinPoint pjp) throws Throwable{        this.printLog("已经记录下操作日志@Around 方法执行前");        pjp.proceed();        this.printLog("已经记录下操作日志@Around 方法执行后");    }    @After("recordLog()")    public void after() {        this.printLog("已经记录下操作日志@After 方法执行后");    }    private void printLog(String str){        System.out.println(str);    }}

代码demo SVN  svn://gitee.com/rainyn/SSM

参考转自 http://outofmemory.cn/code-snippet/3025/spring-AOP-Around-Before-After-differentiate

 

转载于:https://www.cnblogs.com/thiaoqueen/p/7680826.html

你可能感兴趣的文章
Maven2整合集成IntelliJ IDEA创建Web项目
查看>>
实战postfix邮件发送
查看>>
U盘如何量产成USB-CDROM
查看>>
shell批量增删改查百库百表(mysql)
查看>>
网路游侠:日志审计系统与SOC的区别
查看>>
无处不在的网络与中国IPv9
查看>>
hexo
查看>>
云场景实践研究第85期:墨迹天气
查看>>
一个SAP开发人员的2017总结
查看>>
7216:Minecraft
查看>>
上接稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据
查看>>
perl连接mysql的例子
查看>>
windows server 2008虚拟化技术一览
查看>>
webpack2 实践
查看>>
Linux系统日志介绍分析
查看>>
Linux下Tomcat的启动、关闭、杀死进程
查看>>
FTP服务器的防火墙通用设置规则
查看>>
简单记事本及目录树形图的Java实现
查看>>
android 在使用ViewAnimationUtils.createCircularReveal()无法兼容低版本的情况下,另行实现圆形scale动画...
查看>>
Application Virtualization 4.5 部署之(一)
查看>>