需求是這樣的
在已經(jīng)寫(xiě)好的系統(tǒng)中添加管理員的操作記錄。并且總管理權(quán)限可以查看這些記錄。包括操作的時(shí)間 內(nèi)容和操作的結(jié)果以及IP地址。
查找各方面資料后。感覺(jué)最適合我們項(xiàng)目的就是Spring Aop 做切面操作。
操作過(guò)程很簡(jiǎn)單。
首先在 Spring的配置文件中 applicationContext.xml 添加對(duì)aop的掃描并打開(kāi)自動(dòng)代理
<!-- 配置aop -->
<context:component-scan base-package="com.onepay.aop"></context:component-scan>
<!-- 激活自動(dòng)代理 -->
<aop:aspectj-autoproxy proxy-target-class="true" ></aop:aspectj-autoproxy>
在web.xml中添加對(duì)對(duì)webcontext的監(jiān)聽(tīng) 保證隨時(shí)可以取到request和response
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
之后就可以寫(xiě)切面 攔截service的請(qǐng)求
/**
* 登錄操作切面
* @author dell
*
*/
@Component
@Aspect
public class LoginAspect {
@Resource
private HttpServletRequest request;
//配置切點(diǎn)
@Pointcut("execution(* com.onepay.service.WYUserService.*(..))")
public void point(){ }
/*
* 配置前置通知,使用在方法aspect()上注冊(cè)的切入點(diǎn)
* 同時(shí)接受JoinPoint切入點(diǎn)對(duì)象,可以沒(méi)有該參數(shù)
*/
@Before("point()")
public void before(JoinPoint joinPoint){
System.out.println("------------------------");
}
//配置后置通知,使用在方法aspect()上注冊(cè)的切入點(diǎn)
@After("point()")
public void after(JoinPoint joinPoint) throws Throwable{
}
//配置環(huán)繞通知,使用在方法aspect()上注冊(cè)的切入點(diǎn)
@Around("point()")
public Object around(ProceedingJoinPoint joinPoint)throws Throwable{
Object returnVal = joinPoint.proceed();
System.out.println("around 目標(biāo)方法名為:" + joinPoint.getSignature().getName());
System.out.println("around 目標(biāo)方法所屬類(lèi)的簡(jiǎn)單類(lèi)名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("around 目標(biāo)方法所屬類(lèi)的類(lèi)名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("around 目標(biāo)方法聲明類(lèi)型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println("around 第" + (i + 1) + "個(gè)參數(shù)為:" + args[i]);
}
System.out.println("around 返回值:"+returnVal);
//這里必須返回returnVal 否則controller層將得不到反饋。并且這個(gè)returnVal可以在這里修改會(huì)再返回到controller層。
return returnVal;
}
//配置后置返回通知,使用在方法aspect()上注冊(cè)的切入點(diǎn)
@AfterReturning("point()")
public void afterReturn(JoinPoint joinPoint)throws Throwable{
System.out.println("------------------------");
}
//配置拋出異常后通知,使用在方法aspect()上注冊(cè)的切入點(diǎn)
@AfterThrowing(pointcut="point()", throwing="ex")
public void afterThrow(JoinPoint joinPoint, Exception ex){
System.out.println("afterThrow " + joinPoint + "\t" + ex.getMessage());
}
}