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

一:Spring API接口方式

1.1:applicationContext.xml

 1 <bean id="userService" class="com.lieyan.service.UserServiceImpl"/>
 2 <bean id="log" class="com.lieyan.log.Log"/>
 3 <bean id="afterLog" class="com.lieyan.log.Afterlog"/>
 4 
 5 <!--    SpringAPI接口方式一-->
 6 <!--    配置aop-->
 7     <aop:config>
 8 <!--        切入点-->
 9         <aop:pointcut id="pointcut" expression="execution(* com.lieyan.service.UserServiceImpl.*(..))"/>
10 <!--        执行环绕增加-->
11         <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
12         <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
13     </aop:config>

 

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     <bean id="diy" class="com.lieyan.diy.DiyPointCut"/>
 2     <aop:config>
 3 <!--        自定义切换,ref要引用的类-->
 4         <aop:aspect ref="diy">
 5 <!--            切入点-->
 6             <aop:pointcut id="point" expression="execution(* com.lieyan.service.UserServiceImpl.*(..))"/>
 7 <!--            通知-->
 8             <aop:before method="before" pointcut-ref="point"/>
 9             <aop:after method="after" pointcut-ref="point"/>
10         </aop:aspect>
11     </aop:config>

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         <bean id="annotationPointCut" class="com.lieyan.diy.AnnotationPointCut"/>
2 <!--        开启注解支持-->
3         <aop:aspectj-autoproxy/>

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 }

 

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

上一篇:KDE下,Eclipse总是崩溃的解决方法


下一篇:[新手指南参考]阿里云服务器ecs实例选择(地域+CPU+操作系统+带宽)