spring实现service层日志管理

来源:互联网 发布:excel问卷数据录入 编辑:程序博客网 时间:2024/06/07 17:52

现在为了便于管理系统,配置一个日志表,当用户登录系统以及对系统数据进行增删改操作时要将用户的信息存入到数据库

//1.自定义注解

package com.zipx.util.systemlog;

import java.lang.annotation.Documented;

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


/**
 * 自定义注解 拦截service的日志
 * @author 赵宝旗
 *
 */
@Target({ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServicelog {
    
    String description() default "";
}



2.实现拦截添加修改删除操作的业务


package com.zipx.util.systemlog;


import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.*;

import com.zipx.entity.SystemLog;
import com.zipx.entity.system.SystemUser;
import com.zipx.service.LogService;
import com.zipx.util.Const;

/**
 * 创建切点类
 *
 * @author 赵宝旗
 *
 */
@Aspect
@Component
public class SystemLogAspect {
    // 注入service将日志保存到数据库
    @Resource
    private LogService logService;
    // 本地异常日志记录对象
    private static final Logger logger = LoggerFactory
            .getLogger(SystemLogAspect.class);

    // service层的且切点
    @Pointcut("execution(* com.zipx.service..*(..))")
    public void serviceAspect() {

    }

    // 前置通知用于拦截service层的日志
    @Before("serviceAspect()")
    public void doAfter(JoinPoint joinPoint) throws Exception {
        // 获取包括包名在内的全方法名
        String allmethodName = joinPoint.getTarget().getClass().getName() + "."
                + joinPoint.getSignature().getName() + "()";

        // 获取请求的方法
        String requstMethodName = joinPoint.getSignature().getName() + "()";
        // 判断如果是查询方法就不记录到数据库里面insert update delete
        String methodName = requstMethodName.substring(0, 6);
        // requstMethodName.startsWith(prefix, 0)
        if (methodName.equals("insert") || methodName.equals("update")
            || methodName.equals("delete") || methodName.equals("create")
            || methodName.equals("save") || methodName.equals("add")) {

            if (RequestContextHolder.getRequestAttributes() != null) {

                int systemUserId;
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes()).getRequest();
                SystemUser user = (SystemUser) request.getSession()
                        .getAttribute(Const.SESSION_USER);
                if (request == null) {
                    systemUserId = 0;
                }
                // 读取session里面的用户

                if (user == null) {
                    systemUserId = 0;
                } else {
                    systemUserId = user.getsystemUserID();
                }

                // 获取请求的ip
                String ip = request.getRemoteAddr();

                SystemLog log = new SystemLog();
                log.setSystemUserId(systemUserId);
                log.setMethodName(allmethodName);
                log.setIp(ip);
                log.setCreatedDate(new Date());
                log.setDescription(getServiceMethodDescription(joinPoint));
                logService.SystemLog(log);
            }
        }

    }

    /**
     * 获取注解中对方法的描述信息 用于service层注解
     *
     * @throws ClassNotFoundException
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint)
            throws ClassNotFoundException {

        // String targetName = .getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = joinPoint.getTarget().getClass();// Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    if (method.getAnnotation(SystemServicelog.class) != null) {

                        description = method.getAnnotation(
                                SystemServicelog.class).description();
                        if (description == null) {
                            description = "";
                        }
                        break;
                    }
                }
            }
        }
        return description;

    }

}

3.在service对应的添加修改删除方法加入注解


@SystemServicelog(description = "删除订单")
    public boolean deleteOrderInfoByOrderId(String orderId) throws Exception {
        if (orderId.equals("")) {
            return false;
        }
        PageData pd = new PageData();
        pd.put("orderId", orderId);
        Integer i = (Integer) dao.update("OrderHeaderMapper.deleteOrderInfoByOrderId", pd);
        if (i > 0) {
            OrderHeader oh = findOrderByOrderID(Integer.valueOf(orderId));
            if (oh.getPrealertId() != null) {
                // 修改prealert状态为OrderDeleted
                if (prealertService.updatePrealertStatus(oh.getPrealertId(), "OrderDeleted")) {
                    return true;
                }
            }
        }
        return false;
    }




0 0