Spring AOP一直是Spring的一個比較有特色的功能,利用它可以在現有的代碼的任何地方,嵌入我們所想的邏輯功能,並且不需要改變我們現有的代碼結構。
鑒於此,現在的系統已經完成了所有的功能的開發,我們需要把系統的操作日志記錄起來,以方便查看某人某時執行了哪一些操作。Spring AOP可以方便查看到某人某時執行了哪一些類的哪一些方法,以及對應的參數。但是大部分終端用戶看這些方法的名稱時,並不知道這些方法名代碼了哪一些操作,於是方法名對應的方法描述需要記錄起來,並且呈現給用戶。我們知道,AOP攔截了某些類某些方法后,我們可以取得這個方法的詳細定義,通過詳細的定義,我們可以取得這個方法對應的注解,在注解里我們就可以比較方便把方法的名稱及描述寫進去。於是,就有以下的注解定義。代碼如下所示:
在我們需要攔截的方法中加上該注解:
public class AppUserAction extends BaseAction { /** * 添加及保存操作 */ @Action(description="添加或保存用戶信息") public String save() { .... } /** * 修改密碼 * @return */ @Action(description="修改密碼") public String resetPassword() { .... } }
現在設計我們的系統日志表,如下所示:
設計嵌入的邏輯代碼,以下類為所有Struts Action的方法都需要提前執行的方法。(對於get與set的方法除外,對於沒有加上Action注解的也除外)
package com.htsoft.core.log; import java.lang.reflect.Method; import java.util.Date; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import com.htsoft.core.util.ContextUtil; import com.htsoft.oa.model.system.AppUser; import com.htsoft.oa.model.system.SystemLog; import com.htsoft.oa.service.system.SystemLogService; public class LogAspect { @Resource private SystemLogService systemLogService; private Log logger = LogFactory.getLog(LogAspect.class); public Object doSystemLog(ProceedingJoinPoint point) throws Throwable { String methodName = point.getSignature().getName(); // 目標方法不為空 if (StringUtils.isNotEmpty(methodName)) { // set與get方法除外 if (!(methodName.startsWith("set") || methodName.startsWith("get"))) { Class targetClass = point.getTarget().getClass(); Method method = targetClass.getMethod(methodName); if (method != null) { boolean hasAnnotation = method.isAnnotationPresent(Action.class); if (hasAnnotation) { Action annotation = method.getAnnotation(Action.class); String methodDescp = annotation.description(); if (logger.isDebugEnabled()) { logger.debug("Action method:" + method.getName() + " Description:" + methodDescp); } //取到當前的操作用戶 AppUser appUser=ContextUtil.getCurrentUser(); if(appUser!=null){ try{ SystemLog sysLog=new SystemLog(); sysLog.setCreatetime(new Date()); sysLog.setUserId(appUser.getUserId()); sysLog.setUsername(appUser.getFullname()); sysLog.setExeOperation(methodDescp); systemLogService.save(sysLog); }catch(Exception ex){ logger.error(ex.getMessage()); } } } } } } return point.proceed(); } }
通過AOP配置該注入點:
<aop:aspectj-autoproxy/> <bean id="logAspect" class="com.htsoft.core.log.LogAspect"/> <aop:config> <aop:aspect ref="logAspect"> <aop:pointcut id="logPointCut" expression="execution(* com.htsoft.oa.action..*(..))"/> <aop:around pointcut-ref="logPointCut" method="doSystemLog"/> </aop:aspect> </aop:config>
注意,由於AOP的默認配置是使用代理的方式進行嵌入代碼運行,而StrutsAction中若繼承了ActionSupport會報錯誤,錯誤是由於其使用了默認的實現接口而引起的。所以Action必須為POJO類型。
如我們操作了后台的修改密碼,保存用戶信息的操作后,系統日志就會記錄如下的情況。