ITeye博客

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

man1900 · 2010-04-20 10:15 · Spring · 行业应用 · Markdown

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() {
              ....
        }
}

 

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

 

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

 

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

 

评论(12)

  1. #12 楼 · 刘琪琪1994 · 2014-07-28 10:14

    你好,为什么使用这个方法后会在action中执行具体方法操作的时候报空指针异常呢?能不能给个源码下载啊?

  2. #11 楼 · luoyu-ds · 2013-04-10 10:48

    楼主,只有配置好的方法,AOP的代码一进入就会报一个错 WARN OgnlValueStack:60line -Error setting expression 'wareHouse.remarks' with value '[Ljava.lang.String;@7cea5504' ognl.OgnlException: target is null for setProperty(null, "remarks", [Ljava.lang.String;@7cea5504)

  3. #10 楼 · tuto22 · 2012-07-29 21:14

    man1900 writes:

    我们的action层是所有的业务处理的调用(即代表业务意义),service层是业务处理,如保存方法也在service层,但这个保存方法还会被其他service调用,这样,其他业务类调用这个service方法也被拦截的话,这里记录就多一些东西了。

    如果事务写在service层的话日志应该也写在service,要不然一个action调用了两个事务其中一个成功另一个没有成功日志就不好记录了

  4. #9 楼 · glassesbamboo · 2012-06-19 08:59
    Method method = targetClass.getMethod(methodName); 
    

    这一段当方法有参数的时候就会无法获取到正确的method. 这样获得到的method没问题

    			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    			Method method = signature.getMethod();
    
  5. #8 楼 · man1900 · 2011-07-15 16:12

    我们的action层是所有的业务处理的调用(即代表业务意义),service层是业务处理,如保存方法也在service层,但这个保存方法还会被其他service调用,这样,其他业务类调用这个service方法也被拦截的话,这里记录就多一些东西了。

  6. #7 楼 · javafansmagic · 2011-07-15 14:18

    为什么在Action层,不在Service层加注解?

  7. #6 楼 · javafansmagic · 2011-07-14 21:48

    man1900 writes:

    [code=java] /** * 从上下文取得当前用户 * @return */ public static AppUser getCurrentUser(){ SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext != null) { Authentication auth = securityContext.getAuthentication(); if (auth != null) { Object principal = auth.getPrincipal(); if (principal instanceof AppUser) { return (AppUser) principal; } } else { logger.warn("WARN: securityContext cannot be lookuped using SecurityContextHolder."); } } return null; }

    [/code]

    这是Spring Security框架的代码,非作者自己封装的;去Spring官网下载。

  8. #5 楼 · archie2010 · 2011-03-17 09:04

    LZ,代码样例发下不?1021938637@qq.com,如果Action为实现功以能必须继承ActionSupport那该怎样做呢??

  9. #4 楼 · JavaLanguageFun · 2010-07-27 15:43

    所以Action必须为POJO类型。

    这句话何解?Action指的是哪个中Action 是哪个注解 ? 还是其他的访问的Action。为POJO类型 ? 好像本来就是POJO类型啊 。

    请指教!

  10. #3 楼 · taoyu3781212 · 2010-07-15 14:11

    :idea: 不错,值得学习

  11. #2 楼 · man1900 · 2010-06-22 09:14
    
    /**
    	 * 从上下文取得当前用户
    	 * @return
    	 */
    	public static AppUser getCurrentUser(){
    		SecurityContext securityContext = SecurityContextHolder.getContext();
            if (securityContext != null) {
                Authentication auth = securityContext.getAuthentication();
                if (auth != null) {
                    Object principal = auth.getPrincipal();
                    if (principal instanceof AppUser) {
                        return (AppUser) principal;
                    }
                } else {
                    logger.warn("WARN: securityContext cannot be lookuped using SecurityContextHolder.");
                }
            }
            return null;
    	}
    	
    
    
  12. #1 楼 · yourgame · 2010-06-20 13:34

    请公开这个方法或者类的源码,谢谢

    ContextUtil.getCurrentUser();  
    

评论功能维护中,当前仅展示历史评论。