Spring AOP小例子

来源:互联网 发布:软件发信息 编辑:程序博客网 时间:2024/06/11 19:35

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

/** * 业务类 */public class AspectBiz {    public void biz(){        System.out.println("AspectBiz biz.");        throw new RuntimeException();    }}

/** * 日志类 */public class MoocAspect {    public  void before(){        System.out.println("MoocAspect before.");    }    public void afterReturning(){        System.out.println("MoocAspect afterReturing.");    }    public void afterThroing(){        System.out.println("MoocAspect afterThrowing.");    }    public void after(){        System.out.println("MoocAspect after.");    }}
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"       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">    <!-- 我们要插入的日志等-->    <bean id="moocAspect" class="com.mr.three.MoocAspect"></bean>    <!--业务bean-->    <bean id="aspectBiz" class="com.mr.three.AspectBiz"/>    <aop:config>        <!-- 用到哪个处理类-->        <aop:aspect id="moocAspectAOP" ref="moocAspect">            <!-- 切点,要插入到什么地方,expression可以为包,类和方法-->            <aop:pointcut expression="execution(* com.mr.three.*Biz.*(..))" id="moocPointcut"/>            <!-- 切点之前-->            <aop:before method="before" pointcut-ref="moocPointcut"/>            <aop:after-returning method="afterReturning" pointcut-ref="moocPointcut"/>            <aop:after-throwing method="afterThroing" pointcut-ref="moocPointcut"/>            <aop:after method="after" pointcut-ref="moocPointcut"/>        </aop:aspect>    </aop:config></beans>
测试:

public class AdviceTest {    @Test    public void beforeTest(){        ApplicationContext context=new ClassPathXmlApplicationContext("spring-injection.xml");        AspectBiz biz=(AspectBiz)context.getBean("aspectBiz");        biz.biz();    }}
结果:

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