AOP实战---对用户/角色/规则操作日志记录

1.导入jar包   JDK1.7的 aop jar包必须用1.7版本的

aspectjrt-1.7.4.jar /aspectjweaver-1.7.4.jar

<dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.7.4</version>
        </dependency>
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.4</version>

</dependency>

2.配置

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 加入Aspectj配置   注解配置-->
 <aop:aspectj-autoproxy />

package com.pingan.insurance.roadassistant.service.serviceImpl;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.pingan.common.Constants;
import com.pingan.common.model.BusResult;
import com.pingan.insurance.roadassistant.dao.RoleMapper;
import com.pingan.insurance.roadassistant.dao.RuleInstanceMapper;
import com.pingan.insurance.roadassistant.dao.UserMapper;
import com.pingan.insurance.roadassistant.model.OperationLog;
import com.pingan.insurance.roadassistant.model.Provider;
import com.pingan.insurance.roadassistant.model.Role;
import com.pingan.insurance.roadassistant.model.RuleAllot;
import com.pingan.insurance.roadassistant.model.RuleAllotPersents;
import com.pingan.insurance.roadassistant.model.RuleInstance;
import com.pingan.insurance.roadassistant.model.User;
import com.pingan.insurance.roadassistant.service.OperationLogService;

 
/**
 * 日志记录,添加、删除、修改方法AOP
 * @author jiangweiwei336
 *
 */
@Aspect
@Component
public class LogAspect {  
      
    @Autowired  
    private OperationLogService logService;//日志记录Service
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RuleInstanceMapper ruleInstanceMapper;
    
    private static Logger logger = Logger.getLogger(LogAspect.class);
    
    /** 
     * 添加业务逻辑方法切入点 
     */  
    @Pointcut("execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.insert*(..))"
    		+ "||execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.create*(..))")  
    public void insertServiceCall() { }  
      
    /** 
     * 修改业务逻辑方法切入点 
     */  
    @Pointcut("execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.update*(..))"
    		//+ "execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.bind*(..))"
    		+ "||execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.reset*(..))")  
    public void updateServiceCall() { } 
    
    /** 
     * 用户绑定角色方法切入点 
     */  
    @Pointcut("execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.bind*(..))")  
    public void bindServiceCall() { }
    
    /** 
     * 删除业务逻辑方法切入点 
     */  
    @Pointcut("execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.delete*(..))"
    		+ "||execution(* com.pingan.insurance.roadassistant.service.serviceImpl.*.forbid*(..))")  
    public void deleteServiceCall() { }  
      
    /** 
     * 管理员添加操作日志(后置通知) 
     * @param joinPoint 
     * @param rtv 
     * @throws Throwable 
     */  
    @AfterReturning(value="insertServiceCall()", argNames="rtv", returning="rtv")  
    public void insertServiceCallCalls(JoinPoint joinPoint, Object rtv) throws Throwable{  
    	if(rtv instanceof BusResult){
    		BusResult busResult=(BusResult) rtv;
    		String rtnCode = busResult.getRtnCode();
    		if(rtnCode.equals(Constants.SUCCESS)){
        		try {
        			logAddOperation(joinPoint);
        		} catch (Exception e) {
        			logger.info("记录新增日志异常信息"+e.getMessage());
        		}
        	}
    	}else if(rtv instanceof String){
    		String data=(String) rtv;
    		if(data!=null){
    			try {
        			logAddOperation(joinPoint);
        		} catch (Exception e) {
        			logger.info("记录新增日志异常信息"+e.getMessage());
        		}
    		}
    	}
    }

	private void logAddOperation(JoinPoint joinPoint) {
		//获取参数
		Object object = joinPoint.getArgs()[0];
		if(object instanceof User){
			User user=(User) joinPoint.getArgs()[0];
			String userJson = JSONObject.toJSONString(user);
			String username=user.getCreatedUser();
			String userId = user.getUserId();
			String contentType="user";
			logAdd(userJson, username,contentType,userId);
		}else if(object instanceof Role){
			Role role=(Role) joinPoint.getArgs()[0];
			String roleJson = JSONObject.toJSONString(role);
			String username=role.getCreatedUser();
			String roleId = role.getRoleId();
			String contentType="role";
			logAdd(roleJson, username,contentType,roleId);
		}else if(object instanceof RuleInstance){
			RuleInstance ruleInstance=(RuleInstance) joinPoint.getArgs()[0];
			String ruleInstanceJson = JSONObject.toJSONString(ruleInstance);
			String username=ruleInstance.getCreator();
			String code = ruleInstance.getCode();
			String contentType="ruleInstance";
			logAdd(ruleInstanceJson, username,contentType,code);
		}else if(object instanceof RuleAllot){
			RuleAllot ruleAllot=(RuleAllot) joinPoint.getArgs()[0];
			String ruleAllotJson = JSONObject.toJSONString(ruleAllot);
			String username=ruleAllot.getCreator();
			List<RuleAllotPersents> list = ruleAllot.getRuleAllotPersents();
			RuleAllotPersents ruleAllotPersents = list.get(0);
			String code = ruleAllotPersents.getInstanceCode();
			String contentType="ruleInstance";
			logAdd(ruleAllotJson, username,contentType,code);
		}else if(object instanceof Provider){
			Provider provider=(Provider) joinPoint.getArgs()[0];
			String providerJson = JSONObject.toJSONString(provider);
			String username=provider.getCreator();
			String contentType="provider";
			String providerCode = provider.getProviderCode();
			logAdd(providerJson, username, contentType, providerCode);
		}
	}

	private void logAdd(String content,String username,String contentType,String contentId) {
		//创建日志对象  
        OperationLog operationLog=new OperationLog();
        operationLog.setUsername(username);//设置管理员id  
        operationLog.setCreatedTime(new Date());//操作时间  
        operationLog.setNewContent(content);//操作内容  
        operationLog.setOperationType("新增");//操作  
        operationLog.setContentType(contentType);//操作内容类型
        operationLog.setContentId(contentId);//操作内容ID
          
        logService.log(operationLog);//添加日志  
        
	}  
      
    /** 
     * 修改操作日志(环绕通知 可查询出修改前内容作对比)
     * @param joinPoint 
     * @param rtv 
     * @throws Throwable 
     */  
	@Around(value="updateServiceCall()", argNames="rtv")  
    public Object updateServiceCallCalls(ProceedingJoinPoint pjp) throws Throwable{  
		Object result=null;
		
    	try {
			//获取参数
			Object object = pjp.getArgs()[0];
			if(object instanceof User){
				User user=(User) pjp.getArgs()[0];
				//先查询出原有内容
				String userName = user.getUsername();
				User oldUser = userMapper.selectByUserName(userName);
				String oldUserJson = JSONObject.toJSONString(oldUser);
				
				result=pjp.proceed(); //执行修改操作---返回result
				
				String newUserJson = JSONObject.toJSONString(user);
				String username=user.getModifyUser();
				String userId = user.getUserId();
				String contentType="user";
				logUpdate(oldUserJson,newUserJson, username,contentType,userId);
			}else if(object instanceof Role){
				Role role=(Role) pjp.getArgs()[0];
				//先查询出原有内容
				String roleName = role.getRoleName();
				Role oldRole = roleMapper.selectRolesByName(roleName);
				String oldRoleJson = JSONObject.toJSONString(oldRole);
				
				result=pjp.proceed(); //执行修改操作
				
				String newRoleJoson = JSONObject.toJSONString(role);
				String username=role.getModifyUser();
				String newRoleId = role.getRoleId();
				String contentType="role";
				logUpdate(oldRoleJson,newRoleJoson, username,contentType,newRoleId);
			}else if(object instanceof RuleInstance){
				RuleInstance ruleInstance=(RuleInstance) pjp.getArgs()[0];
				//先查询出原有内容
				String code = ruleInstance.getCode();
				RuleInstance oldRuleInstance = ruleInstanceMapper.selectByRuleCode(code);
				String oldRuleInstanceJson = JSONObject.toJSONString(oldRuleInstance);
				
				result=pjp.proceed(); //执行修改操作
				
				String newRuleInstanceJson = JSONObject.toJSONString(ruleInstance);
				String username=ruleInstance.getModifier();
				String newCode = ruleInstance.getCode();
				String contentType="ruleInstance";
				logUpdate(oldRuleInstanceJson,newRuleInstanceJson, username,contentType,newCode);
			}else if(object instanceof RuleAllot){
				RuleAllot ruleAllot=(RuleAllot) pjp.getArgs()[0];
				//先查询出原有内容
				String code = ruleAllot.getAllotCode();
				RuleInstance oldRuleInstance = ruleInstanceMapper.selectByRuleCode(code);
				String oldRuleInstanceJson = JSONObject.toJSONString(oldRuleInstance);
				
				result=pjp.proceed(); //执行修改操作
				
				String newRuleInstanceJson = JSONObject.toJSONString(ruleAllot);
				String username=ruleAllot.getModifier();
				String newCode = ruleAllot.getAllotCode();
				String contentType="ruleInstance";
				logUpdate(oldRuleInstanceJson,newRuleInstanceJson, username,contentType,newCode);
			}else if(object instanceof String){
				//说明是resetPassword 参数为string
				String userId = (String) pjp.getArgs()[0];
				String username = (String) pjp.getArgs()[1];
				User user = userMapper.selectByPrimaryKey(userId);
				String userJson = JSONObject.toJSONString(user);
				
				result=pjp.proceed(); //执行修改操作
				
				OperationLog operationLog=new OperationLog();
		        operationLog.setUsername(username);//设置管理员id  
		        operationLog.setCreatedTime(new Date());//操作时间  
		        operationLog.setOldContent(userJson);//旧内容
		        operationLog.setOperationType("用户重置密码");//操作  
		        operationLog.setContentType("user");//操作内容类型
		        operationLog.setContentId(userId);//操作内容ID
		        logService.log(operationLog);//添加日志  
			}else if(object instanceof List){
				@SuppressWarnings("unchecked")
				List<RuleInstance> list=(List<RuleInstance>)pjp.getArgs()[0];
				String listString = JSONObject.toJSONString(list);
				String username= (String) pjp.getArgs()[1];
				
				result=pjp.proceed(); //执行修改操作
				OperationLog operationLog=new OperationLog();
		        operationLog.setUsername(username);//设置管理员id  
		        operationLog.setCreatedTime(new Date());//操作时间  
		        operationLog.setOperationType("设置规则优先级");//操作  
		        operationLog.setContentType("RuleInstance");//操作内容类型
		        operationLog.setNewContent(listString);
		        logService.log(operationLog);//添加日志  
			}
		} catch (Exception e) {
			logger.info("记录更新日志异常信息"+e.getMessage());
		}
    	return result; 
    } 
	
	/** 
     * 用户绑定角色操作日志(环绕通知) 
     * @param joinPoint 
     * @param rtv 
     * @throws Throwable 
     */  
	@Around(value="bindServiceCall()", argNames="rtv")  
    public Object bindServiceCallCalls(ProceedingJoinPoint pjp) throws Throwable{  
		Object result=null;
    	try {
			//获取参数
			User user=(User) pjp.getArgs()[0];
			//先查询出原有内容
			String userId = user.getUserId();
			User oldUser=userMapper.selectByPrimaryKey(userId);
			String oldUserJson = JSONObject.toJSONString(oldUser);
			
			result=pjp.proceed(); //执行修改操作
			
			String newUserJson = user.toString();
			//String newUserJson = JSONObject.toJSONString(oldUser);
			String username=user.getModifyUser();
			String contentType="user";
			logUpdate(oldUserJson,newUserJson, username,contentType,userId);
		} catch (Exception e) {
			logger.info("记录更新日志异常信息"+e.getMessage());
		}
    	return result; 
    } 
    
    private void logUpdate(String oldContent,String newContent,String username,String contentType,String contentId) {
		//创建日志对象  
        OperationLog operationLog=new OperationLog();
        operationLog.setUsername(username);//设置管理员id  
        operationLog.setCreatedTime(new Date());//操作时间  
        operationLog.setOldContent(oldContent);//旧内容
        operationLog.setNewContent(newContent);//新内容  
        operationLog.setOperationType("修改");//操作  
        operationLog.setContentType(contentType);//操作内容类型
        operationLog.setContentId(contentId);//操作内容ID
          
        logService.log(operationLog);//添加日志  
	}  
      
    /** 
     * 删除操作(后置通知 只记录删除的id)
     * @param joinPoint 
     * @param rtv 
     * @throws Throwable 
     */  
    @AfterReturning(value="deleteServiceCall()", argNames="rtv",returning="rtv")  
    public void deleteCallCalls(JoinPoint joinPoint, Object rtv) throws Throwable {  
    	String contentId = (String) joinPoint.getArgs()[0];
    	String username=(String) joinPoint.getArgs()[1];
    	//创建日志对象  
        OperationLog operationLog=new OperationLog();
        operationLog.setUsername(username);//设置管理员id  
        operationLog.setCreatedTime(new Date());//操作时间  
        operationLog.setOperationType("删除");//操作  
        operationLog.setContentId(contentId);//操作内容ID
          
        logService.log(operationLog);//添加日志  
    }  
      
    /** 
     * 使用Java反射来获取被拦截方法(insert、update)的参数值, 
     * 将参数值拼接为操作内容 
     */  
    public String adminOptionContent(Object[] args, String mName) throws Exception{  
        if (args == null) {  
            return null;  
        }  
        StringBuffer rs = new StringBuffer();  
        rs.append(mName);  
        String className = null;  
        int index = 1;  
        // 遍历参数对象  
        for (Object info : args) {  
            //获取对象类型  
            className = info.getClass().getName();  
            className = className.substring(className.lastIndexOf(".") + 1);  
            rs.append("[参数" + index + ",类型:" + className + ",值:");  
            // 获取对象的所有方法  
            Method[] methods = info.getClass().getDeclaredMethods();  
              
            // 遍历方法,判断get方法  
            for (Method method : methods) {  
                String methodName = method.getName();  
                // 判断是不是get方法  
                if (methodName.indexOf("get") == -1) {// 不是get方法  
                    continue;// 不处理  
                }  
                  
                Object rsValue = null;  
                try {  
                    // 调用get方法,获取返回值  
                    rsValue = method.invoke(info);  
                    if (rsValue == null) {//没有返回值  
                        continue;  
                    }  
                } catch (Exception e) {  
                    continue;  
                }  
                //将值加入内容中  
                rs.append("(" + methodName + " : " + rsValue + ")");  
            }  
            rs.append("]");  
            index++;  
        }  
        return rs.toString();  
    }  
} 

 

转载于:https://my.oschina.net/u/3278373/blog/874566

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值