SpringAOP
public class UserSerciceLogger(){
//前置增强
public void before(JoinPoint jp){
Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,方法入参:"+Arrays.toString(jp.getArgs()));
}
//后置增强
public void after(JoinPoint jp,Object result){
Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法返回值:"+result);
}
//异常抛出增强(相当于异常处理的finally块)
public void afterThrowing(JoinPoint jp,RuntimeException e){
}
//最终增强
public void afterLog(JoinPoint jp){
}
//环绕增强
public Object around(ProceedingJoinPoint jp){
Object result=jp.proceed();//执行目标方法并获得返回值
return result;
}
}
appliactionContext.xml
<!--根据切入点的类创建Bean-->
<bean id="theLogger" calss="cn.a.aop.UserSerciceLogger"></bean>
<!--aop的配置节点-->
<aop:config>
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(public void xxx(xxx))"/><!--匹配方法 上图有详细说明-->
<aop:aspect ref="theLogger"><!--theLogger是切入点的类创建的bean-->
<!--前置增强-->
<aop:before method="before" pointcut-ref="pointcut"></aop:before>
<!--后置增强-->
<aop:after-returning method="after" pointcut-ref="pointcut" returning="result"/>
<!--异常抛出增强-->
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
<!--最终增强-->
<aop:after method="afterLog" pointcut-ref="pointcut"/>
<!--环绕增强-->
<aop:around method="around" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
调用
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("bean节点的名字");//相当于创建对象
使用注解定义切面
@Aspect
public class UserSerciceLogger(){
//前置增强
@Before("execution( )")
public void before(JoinPoint jp){
Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,方法入参:"+Arrays.toString(jp.getArgs()));
}
//后置增强
@AfterRuturning( pointcut = "execution( )" , returning="result")
public void after(JoinPoint jp,Object result){
Syso("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法返回值:"+result);
}
//异常抛出增强(相当于异常处理的finally块)
@AfterThrowing( pointcut = "execution( )" , throwing="e")
public void afterThrowing(JoinPoint jp,RuntimeException e){
}
//最终增强
@After( pointcut = "execution( )" )
public void afterLog(JoinPoint jp){
}
//环绕增强
@Around( pointcut = "execution( )" , returning="result")
public Object around(ProceedingJoinPoint jp){
Object result=jp.proceed();//执行目标方法并获得返回值
return result;
}
}
AppliactionContext.xml
<context:component-scan base-package="包名"/>
<bean class="UserSerciceLogger"/>
<aop:aspectj-autoproxy/>