aop
aop:面向切面编程,它可以解决重复代码。
aop有两种方式:
一、.xml方式
1、在springmvc-servlet.xml中配置aop,应用bean文件;
<!--aop配置-->
<aop:config>
<aop:aspect id="log" ref="loging">
<!--第一个星号:返回值
第二个星号:类
第三个星号:方法
小括号:方法入参-->
<aop:pointcut id="print" expression="execution(* com.dait.controller.*.*(..))"/>
<!-- <aop:before pointcut-ref="print" method="doBefore"/>
<aop:after pointcut-ref="print" method="doAfter"/>-->
<aop:around pointcut-ref="print" method="doAround"/>
<aop:after-throwing pointcut-ref="print" method="doThrowing" throwing="ex"/>
</aop:aspect>
</aop:config>
2、在bean文件的类上加@Component
@Component
public class Loging {
/**
* 目标方法执行之前调用
* @param
*/
/* public void doBefore(JoinPoint jp) {
System.out.println(">>>>>doBefore>>>>>>>log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
}*/
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println(">>>>>doAround>>>>>>>log Begining method: " + pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName());
Object retVal = pjp.proceed();//执行目标方法
System.out.println(">>>>>doAround>>>>>>>log Ending method: " + pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName());
return retVal;
}
}
二、采用注解的方式
1、在springmvc-servlet.xml文件中添加注解配置
<!--启用注解代理-->
<aop:aspectj-autoproxy/>
2、在bean文件上添加@Component和@Aspect,缺一不可
@Component
@Aspect
public class LogingAnnotation {
public void doBefore(JoinPoint jp) {
System.out.println(">>>>>doBefore>>>>>>>log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
}
@Around("execution(* com.dait.controller.*.*(..))")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long time = System.currentTimeMillis();
System.out.println(">>>>>doAround>>>>>>>log Begining method: " + pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName());
Object retVal = pjp.proceed();//执行目标方法
System.out.println(">>>>>doAround>>>>>>>log Ending method: " + pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName());
time = System.currentTimeMillis() - time;
//pjp.getTarget().getClass().getName() 目前类包+类名
//pjp.getSignature().getName() 目标方法
return retVal;
}
public void doAfter(JoinPoint jp) {
System.out.println(">>anno>>>doAfter>>>>>>>log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
}
public void doThrowing(JoinPoint jp, Throwable ex) {
System.out.println(">>anno>>>doThrowing>>>>>>>method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + " throw exception");
System.out.println(ex.getMessage());
}
}