阅读 66

AOP面向切面编程的三种方式

一:Spring API接口方式

1.1:applicationContext.xml

 1 "userService" class="com.lieyan.service.UserServiceImpl"/>
 2 "log" class="com.lieyan.log.Log"/>
 3 "afterLog" class="com.lieyan.log.Afterlog"/>
 4 
 5 
 6 
 7     
 8 
 9         "pointcut" expression="execution(* com.lieyan.service.UserServiceImpl.*(..))"/>
10 
11         ref="log" pointcut-ref="pointcut"/>
12         ref="afterLog" pointcut-ref="pointcut"/>
13     

 

1.2:log

1 public class Log implements MethodBeforeAdvice {
2     public void before(Method method, Object[] objects, Object target) throws Throwable {
3         System.out.println(target.getClass().getName()+""+method.getName()+"被执行了");
4     }
5 }

1.3:Afterlog

1 public class Afterlog implements AfterReturningAdvice {
2     public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
3         System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
4     }
5 }

 

二:自定义

2.1:applicationContext.xml

 1     "diy" class="com.lieyan.diy.DiyPointCut"/>
 2     
 3 
 4         ref="diy">
 5 
 6             "point" expression="execution(* com.lieyan.service.UserServiceImpl.*(..))"/>
 7 
 8             "before" pointcut-ref="point"/>
 9             "after" pointcut-ref="point"/>
10         
11     

2.2:DiyPointCut

1 public class DiyPointCut {
2     public void before(){
3         System.out.println("方法执行前---------");
4     }
5 
6     public void after(){
7         System.out.println("方法执行后----------");
8     }
9 }

 

三:注解

3.1:applicationContext.xml

1         "annotationPointCut" class="com.lieyan.diy.AnnotationPointCut"/>
2 
3         

3.2:

AnnotationPointCut

 1 @Aspect
 2 public class AnnotationPointCut {
 3 
 4     @Before("execution(* com.lieyan.service.UserServiceImpl.*(..))")
 5     public void before(){
 6         System.out.println("方法执行前==========");
 7     }
 8 
 9     @After("execution(* com.lieyan.service.UserServiceImpl.*(..))")
10     public void after(){
11         System.out.println("方法执行后==========");
12     }
13 
14     @Around("execution(* com.lieyan.service.UserServiceImpl.*(..))")
15     public void around(ProceedingJoinPoint jp) throws Throwable{
16         System.out.println("环绕前====");
17 
18         //执行方法
19         Object proceed = jp.proceed();
20 
21         System.out.println("环绕后=====");
22     }
23 }

 

原文:https://www.cnblogs.com/nuyan/p/15265382.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐