分享

利用Spring AOP与JAVA注解为系统增加日志功能

 yespon 2017-06-15
 

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类型。

如我们操作了后台的修改密码,保存用户信息的操作后,系统日志就会记录如下的情况。

查看日志数据表格

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多