您的位置:首页 > 理论基础

aop 环绕通知 可以计算机 程序执行的时间

2016-06-02 17:55 441 查看
1、java代码

@Test
public void testSchemaAroundAdvice() {
System.out.println("======================================");
long start = System.currentTimeMillis();
ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter6/advice.xml");
IHelloWorldService helloworldService = ctx.getBean("helloWorldService", IHelloWorldService.class);
helloworldService.sayAround("haha");
System.out.println("======================================");
long end = System.currentTimeMillis();
System.out.println("end! performance took "+(end-start)+" milliseconds");
}

2、advice.xml中

<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="helloWorldService" class="cn.javass.spring.chapter6.service.impl.HelloWorldService"/>

<bean id="aspect" class="cn.javass.spring.chapter6.aop.HelloWorldAspect"/>

<bean id="beforeAdvice" class="cn.javass.spring.chapter6.aop.BeforeAdviceImpl"/>

<aop:config>
<aop:advisor pointcut="execution(* cn.javass..*.sayAdvisorBefore(..))"
advice-ref="beforeAdvice"/>
<aop:aspect ref="aspect">
<aop:before pointcut="execution(* cn.javass..*.sayBefore(..)) and args(param)"
method="beforeAdvice(java.lang.String)"
arg-names="param"/>
<aop:after-returning pointcut="execution(* cn.javass..*.sayAfterReturning(..))"
method="afterReturningAdvice"
arg-names="retVal"
returning="retVal"/>
<aop:after-throwing pointcut="execution(* cn.javass..*.sayAfterThrowing(..))"
method="afterThrowingAdvice"
arg-names="exception"
throwing="exception"/>

<aop:after pointcut="execution(* cn.javass..*.sayAfterFinally(..))"
method="afterFinallyAdvice"/>

<aop:around pointcut="execution(* cn.javass..*.sayAround(..))"
method="aroundAdvice"/>

<aop:declare-parents types-matching="cn.javass..*.IHelloWorldService+"
implement-interface="cn.javass.spring.chapter6.service.IIntroductionService"
default-impl="cn.javass.spring.chapter6.service.impl.IntroductiondService"/>
</aop:aspect>
</aop:config>

</beans>

3、切面中的 方法
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("===========around before advice");
Object retVal = pjp.proceed(new Object[] {"replace"});
System.out.println("===========around after advice");
return retVal;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息