經過自定義註解,和Spring 的aop 實現插入業務日誌的功能

首先固然是定義一個註解類型了:java

/**
 * 
 * 日誌切面註解
 * @Description: TODO <p>MethodLog.java</p>
 * @做者: 王彥寶
 * @時間: 2018年8月24日上午10:08:08
 * @version V1.0
 * @see java.lang.Class
 * @since JDK{jdk1.7}
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodLog {

    String content() default "";
    MethodLogType operType() default MethodLogType.QUERY;
}

在這個註解中我定義了兩個參數:一個是content:這個是日誌的主要內容,一個是operType : 日誌類型。spring

其中MethodLogType  是我本身定義的一個枚舉類:數據庫

/**
 * methodLog註解參數 operType 的枚舉值
 * 
 * @Description: TODO <p>MethodLogType.java</p>
 * @做者: 王彥寶
 * @時間: 2018年8月24日下午2:21:57
 * @version V1.0
 * @see java.lang.Class
 * @since JDK{jdk1.7}
 */
public enum MethodLogType {

	/* 查詢 */
	QUERY,
	/* 新增 */
	ADD,
	/* 修改 */
	UPDATE,
	/*導出*/
	EXPORTS,
	/*導入*/
	IMPORTS,
	/* 刪除 */
	DELETE;
}

下面就要經過spring  的aop  實現業務日誌插入數據庫了:app

@Component
@Aspect   //
public class LogService {

	
	 	@Resource(name = "SaveLogDao")
	    private SaveLogDao dao;

	    public LogService() {
	    }

	    /**
	     * 切點
	     */
	    @Pointcut("@annotation(com.eimageglobal.iq.client.util.MethodLog)")
	    public void methodCachePointcut() { }


	    /**
	     * 切面
	     *
	     * @param point
	     * @return
	     * @throws Throwable
	     */
	    @Around("methodCachePointcut()")
	    public Object around(ProceedingJoinPoint point) throws Throwable {
	        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
	                .getRequestAttributes()).getRequest();
	        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
	        Calendar ca = Calendar.getInstance();
	        String operDate = df.format(ca.getTime());
	        String methodRemark = getMthodRemark(point);
	        String methodOpertype = getMthodOperType(point);
	        String methodName = point.getSignature().getName();
	        String packages = point.getThis().getClass().getName();
	        if (packages.indexOf("$$EnhancerByCGLIB$$") > -1) { // 若是是CGLIB動態生成的類
	            try {
	                packages = packages.substring(0, packages.indexOf("$$"));
	            } catch (Exception ex) {
	                ex.printStackTrace();
	            }
	        }
	        String operatingcontent = "";
	        Object[] method_param = null;
	        Object object=null;
	        try {
	            method_param = point.getArgs(); //獲取方法參數
	            dao.save(dolog);
	            String param=(String) point.proceed(point.getArgs());
//	            object = point.proceed();
	        } catch (Exception e) {
	            // 異常處理記錄日誌..log.error(e);
	             e.printStackTrace();
	        }
	        return object;

	    }

	    /**
	     * 方法異常時調用
	     *
	     * @param ex
	     */
	    public void afterThrowing(Exception ex) {
	        System.out.println("afterThrowing");
	        System.out.println(ex);
	    }

	    /**
	     * 獲取方法中的中文備註
	     *
	     * @param joinPoint
	     * @return
	     * @throws Exception
	     */
	    public static String getMthodRemark(ProceedingJoinPoint joinPoint) throws Exception {
	        String targetName = joinPoint.getTarget().getClass().getName();
	        String methodName = joinPoint.getSignature().getName();
	        Object[] arguments = joinPoint.getArgs();
	        Class targetClass = Class.forName(targetName);
	        Method[] method = targetClass.getMethods();
	        String methode = "";
	        for (Method m : method) {
	            if (m.getName().equals(methodName)) {
	                Class[] tmpCs = m.getParameterTypes();
	                if (tmpCs.length == arguments.length) {
	                    MethodLog methodCache = m.getAnnotation(MethodLog.class);
	                    if (methodCache != null) {
	                        methode = methodCache.remark();
	                    }
	                    break;
	                }
	            }
	        }
	        return methode;
	    }
	    
	    /**
	     * 獲取方法中的中文備註
	     *
	     * @param joinPoint
	     * @return
	     * @throws Exception
	     */
	    public static String getMthodOperType(ProceedingJoinPoint joinPoint) throws Exception {
	        String targetName = joinPoint.getTarget().getClass().getName();
	        String methodName = joinPoint.getSignature().getName();
	        Object[] arguments = joinPoint.getArgs();
	        Class targetClass = Class.forName(targetName);
	        Method[] method = targetClass.getMethods();
	        MethodLogType methode = null;
	        String type="";
	        for (Method m : method) {
	            if (m.getName().equals(methodName)) {
	                Class[] tmpCs = m.getParameterTypes();
	                if (tmpCs.length == arguments.length) {
	                    MethodLog methodCache = m.getAnnotation(MethodLog.class);
	                    if (methodCache != null) {
	                        methode = methodCache.operType();
	                    }
	                    break;
	                }
	            }
	        }
	        return type=LogType.getName(methode.toString());
	    }

在spring -source.xml  中經過bean  注入  :日誌

<bean id="SaveLogDao" class="com.eimageglobal.iq.biz.dao.impl.SaveLogDaoImpl"/>

這裏的SaveLogDao  就是  LogService  中  
         @Resource(name = "SaveLogDao")
        private SaveLogDao dao;code

       這裏的用到。orm

在業務代碼中的使用樣例:xml

/**
	 *
	 * @param request
	 * @param response
	 * @做者: 王彥寶
	 * @時間: 2018年8月24日下午4:00:55
	 * @返回 void
	 */
	@RequestMapping(value = "XXXXXXXXX")
	@MethodLog(content="這裏是你要插入的日誌內容",operType=MethodLogType.UPDATE)
  	public void updateSort(HttpServletRequest request, HttpServletResponse response){
		
	}

這樣在你須要插入日誌的地方加這樣一個註解就ok 了ip

相關文章
相關標籤/搜索