---
title: "利用Spring AOP与JAVA注解为系统增加日志功能"
author: "man1900"
date: "2010-04-20T10:15:44Z"
tags: []
categories: ["行业应用"]
slug: "spring-aop-java"
draft: false
lastmod: "2010-04-20T10:32:11Z"
id: 648107
url: "https://man1900.iteye.com/blog/648107"
---

Spring AOP一直是Spring的一个比较有特色的功能，利用它可以在现有的代码的任何地方，嵌入我们所想的逻辑功能，并且不需要改变我们现有的代码结构。

 

鉴于此，现在的系统已经完成了所有的功能的开发，我们需要把系统的操作日志记录起来，以方便查看某人某时执行了哪一些操作。Spring AOP可以方便查看到某人某时执行了哪一些类的哪一些方法，以及对应的参数。但是大部分终端用户看这些方法的名称时，并不知道这些方法名代码了哪一些操作，于是方法名对应的方法描述需要记录起来，并且呈现给用户。我们知道，AOP拦截了某些类某些方法后，我们可以取得这个方法的详细定义，通过详细的定义，我们可以取得这个方法对应的注解，在注解里我们就可以比较方便把方法的名称及描述写进去。于是，就有以下的注解定义。代码如下所示：

 

```
package com.htsoft.core.log;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @company  广州宏天软件有限公司
 * @description 类的方法描述注解
 * @author csx
 * @create 2010-02-03
 */
@Target(ElementType.METHOD)   
@Retention(RetentionPolicy.RUNTIME)   
@Documented  
@Inherited  
public @interface Action {
	/**
	 * 方法描述
	 * @return
	 */
	public String description() default "no description"; 
}
```

 

 

在我们需要拦截的方法中加上该注解：

 

 

```
/**
 * 
 * @author csx
 * 
 */
public class AppUserAction extends BaseAction {	
	/**
	 * 添加及保存操作
	 */
	@Action(description="添加或保存用户信息")
	public String save() {
             ....
        }
       /**
	 * 修改密码
	 * 
	 * @return
	 */
	@Action(description="修改密码")
	public String resetPassword() {
              ....
        }
}
```

 

现在设计我们的系统日志表，如下所示：

  ![](http://dl.iteye.com/upload/attachment/237007/521a18fc-8b3e-3b4a-bd6c-d1a606fe71bc.jpg)

设计嵌入的逻辑代码，以下类为所有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类型。

 

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

 

![](http://dl.iteye.com/upload/attachment/237017/27e0023a-91b4-3e71-b062-138a2f686b90.jpg)