Spring AOP环绕通知小例子

深碍√TFBOYSˉ_ 2022-06-15 01:54 307阅读 0赞

不带参数的:

  1. /**
  2. * 日志类
  3. */
  4. public class MoocAspect {
  5. public Object around(ProceedingJoinPoint pjp){
  6. Object obj=null;
  7. try {
  8. System.out.println("MoocAspect around 1.");
  9. obj=pjp.proceed();
  10. System.out.println("MoocAspect around 2.");
  11. } catch (Throwable throwable) {
  12. throwable.printStackTrace();
  13. }
  14. return obj;
  15. }
  16. public Object aroundInit(ProceedingJoinPoint pjp,String bizName,int times){
  17. System.out.println(bizName+" "+times);
  18. Object obj=null;
  19. try {
  20. System.out.println("MoocAspect aroundinit 1.");
  21. obj=pjp.proceed();
  22. System.out.println("MoocAspect aroundinit 2.");
  23. } catch (Throwable throwable) {
  24. throwable.printStackTrace();
  25. }
  26. return obj;
  27. }
  28. }
  29. /**
  30. * 业务类
  31. */
  32. public class AspectBiz {
  33. public void biz(){
  34. System.out.println("AspectBiz biz.");
  35. }
  36. public void init(String bizName,int times){
  37. System.out.println("AspectBiz init:"+bizName+" "+times);
  38. }
  39. }
  40. <?xml version="1.0" encoding="UTF-8"?>
  41. <beans xmlns="http://www.springframework.org/schema/beans"
  42. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  43. xmlns:aop="http://www.springframework.org/schema/aop"
  44. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  45. <!-- 我们要插入的日志等-->
  46. <bean id="moocAspect" class="com.mr.three.MoocAspect"></bean>
  47. <!--业务bean-->
  48. <bean id="aspectBiz" class="com.mr.three.AspectBiz"/>
  49. <aop:config>
  50. <!-- 用到哪个处理类-->
  51. <aop:aspect id="moocAspectAOP" ref="moocAspect">
  52. <!-- 切点,要插入到什么地方,expression可以为包,类和方法-->
  53. <aop:pointcut expression="execution(* com.mr.three.*Biz.*(..))" id="moocPointcut"/>
  54. <aop:around method="around" pointcut-ref="moocPointcut"/>
  55. <aop:around method="aroundInit" pointcut="execution(* com.mr.three.AspectBiz.init(String,int))
  56. and args(bizName,times)"/>
  57. </aop:aspect>
  58. </aop:config>
  59. </beans>
  60. @Test
  61. public void AroundInitTest(){
  62. ApplicationContext context=new ClassPathXmlApplicationContext("spring-injection.xml");
  63. AspectBiz biz=(AspectBiz)context.getBean("aspectBiz");
  64. biz.init("占旭鹏",20);
  65. }

MoocAspect around 1.
张三 20
MoocAspect aroundinit 1.
AspectBiz init:张三 20
MoocAspect aroundinit 2.
MoocAspect around 2.

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读

    相关 基于注解的AOP环绕通知

    基于注解的AOP环绕通知 环绕通知本质上就是环绕通知的这一个方法实现了包括前置通知、返回通知、异常通知、后置通知所有的方法的实现。与动态代理实现的方式一样(方法的内容)

    相关 spring AOP 环绕增强Demo

        前面写了一个[前置增强,后置增强的小demo][demo],前置增强即在方法调用前对方法增强;后置增强即在方法调用后对方法增强。环绕增强允许在目标类方法调用前