Spring AOP小例子

拼搏现实的明天。 2022-06-15 01:52 275阅读 0赞

Spring AOP可以实现在原有的业务代码中加入一些输出,不改变原来的代码,比如日志

  1. /**
  2. * 业务类
  3. */
  4. public class AspectBiz {
  5. public void biz(){
  6. System.out.println("AspectBiz biz.");
  7. throw new RuntimeException();
  8. }
  9. }
  10. /**
  11. * 日志类
  12. */
  13. public class MoocAspect {
  14. public void before(){
  15. System.out.println("MoocAspect before.");
  16. }
  17. public void afterReturning(){
  18. System.out.println("MoocAspect afterReturing.");
  19. }
  20. public void afterThroing(){
  21. System.out.println("MoocAspect afterThrowing.");
  22. }
  23. public void after(){
  24. System.out.println("MoocAspect after.");
  25. }
  26. }
  27. <?xml version="1.0" encoding="UTF-8"?>
  28. <beans xmlns="http://www.springframework.org/schema/beans"
  29. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  30. xmlns:aop="http://www.springframework.org/schema/aop"
  31. 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">
  32. <!-- 我们要插入的日志等-->
  33. <bean id="moocAspect" class="com.mr.three.MoocAspect"></bean>
  34. <!--业务bean-->
  35. <bean id="aspectBiz" class="com.mr.three.AspectBiz"/>
  36. <aop:config>
  37. <!-- 用到哪个处理类-->
  38. <aop:aspect id="moocAspectAOP" ref="moocAspect">
  39. <!-- 切点,要插入到什么地方,expression可以为包,类和方法-->
  40. <aop:pointcut expression="execution(* com.mr.three.*Biz.*(..))" id="moocPointcut"/>
  41. <!-- 切点之前-->
  42. <aop:before method="before" pointcut-ref="moocPointcut"/>
  43. <aop:after-returning method="afterReturning" pointcut-ref="moocPointcut"/>
  44. <aop:after-throwing method="afterThroing" pointcut-ref="moocPointcut"/>
  45. <aop:after method="after" pointcut-ref="moocPointcut"/>
  46. </aop:aspect>
  47. </aop:config>
  48. </beans>

测试:

  1. public class AdviceTest {
  2. @Test
  3. public void beforeTest(){
  4. ApplicationContext context=new ClassPathXmlApplicationContext("spring-injection.xml");
  5. AspectBiz biz=(AspectBiz)context.getBean("aspectBiz");
  6. biz.biz();
  7. }
  8. }

结果:

MoocAspect before.
AspectBiz biz.
MoocAspect afterThrowing.
MoocAspect after.

发表评论

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

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

相关阅读

    相关 Spring-AOP例子

    Spring-AOP例子 > 第一部分是前期准备,第二部分是基于注解的方式配置事务,第三部分基于`.xml`配置文件配置事务 一、准备 > 使用加减乘除方法测试,

    相关 Spring AOP 学习例子

    工作忙,时间紧,不过事情再多,学习是必须的。记得以前的部门老大说过:“开发人员不可能一天到晚只有工作,肯定是需要自我学习。第一:为了更充实自己,保持进步状态。第二:为了提升技术

    相关 SpringAOP实现例子

    一、为什么需要AOP 假如我们应用中有n个业务逻辑组件,每个业务逻辑组件又有m个方法,那现在我们的应用就一共包含了n\m个方法,我会抱怨方法太多。。。现在,我有这样一个需