欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring AOP自定义注解方式实现日志管理的实例讲解

程序员文章站 2023-12-01 08:34:46
今天继续实现aop,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用spring aop 自定义注解形式实现日志管理。废话不多说,直接开始!!! 关于配置我...

今天继续实现aop,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用spring aop 自定义注解形式实现日志管理。废话不多说,直接开始!!!

关于配置我还是的再说一遍。

在applicationcontext-mvc.xml中要添加的

<mvc:annotation-driven />
<!-- 激活组件扫描功能,在包com.gcx及其子包下面自动扫描通过注解配置的组件 -->
<context:component-scan base-package="com.gcx" /> 
  
<!-- 启动对@aspectj注解的支持 --> 
<!-- proxy-target-class等于true是强制使用cglib代理,proxy-target-class默认是false,如果你的类实现了接口 就走jdk代理,如果没有,走cglib代理 -->
<!-- 注:对于单利模式建议使用cglib代理,虽然jdk动态代理比cglib代理速度快,但性能不如cglib -->
<!--如果不写proxy-target-class="true"这句话也没问题-->
<aop:aspectj-autoproxy proxy-target-class="true"/> 
<!--切面-->
<bean id="systemlogaspect" class="com.gcx.annotation.systemlogaspect"></bean>

接下来开始编写代码。

创建日志类实体

public class systemlog {
  private string id;
  private string description;
  private string method;
  private long logtype;
  private string requestip;
  private string exceptioncode;
  private string exceptiondetail;
  private string params;
  private string createby;
  private date createdate;
  public string getid() {
    return id;
  }
  public void setid(string id) {
    this.id = id == null ? null : id.trim();
  }
  public string getdescription() {
    return description;
  }
  public void setdescription(string description) {
    this.description = description == null ? null : description.trim();
  }
  public string getmethod() {
    return method;
  }
  public void setmethod(string method) {
    this.method = method == null ? null : method.trim();
  }
  public long getlogtype() {
    return logtype;
  }
  public void setlogtype(long logtype) {
    this.logtype = logtype;
  }
  public string getrequestip() {
    return requestip;
  }
  public void setrequestip(string requestip) {
    this.requestip = requestip == null ? null : requestip.trim();
  }
  public string getexceptioncode() {
    return exceptioncode;
  }
  public void setexceptioncode(string exceptioncode) {
    this.exceptioncode = exceptioncode == null ? null : exceptioncode.trim();
  }
  public string getexceptiondetail() {
    return exceptiondetail;
  }
  public void setexceptiondetail(string exceptiondetail) {
    this.exceptiondetail = exceptiondetail == null ? null : exceptiondetail.trim();
  }
  public string getparams() {
    return params;
  }
  public void setparams(string params) {
    this.params = params == null ? null : params.trim();
  }
  public string getcreateby() {
    return createby;
  }
  public void setcreateby(string createby) {
    this.createby = createby == null ? null : createby.trim();
  }
  public date getcreatedate() {
    return createdate;
  }
  public void setcreatedate(date createdate) {
    this.createdate = createdate;
  }
}

编写dao接口

package com.gcx.dao;
import com.gcx.entity.systemlog;
public interface systemlogmapper {
  int deletebyprimarykey(string id);
  int insert(systemlog record);
  int insertselective(systemlog record);
  systemlog selectbyprimarykey(string id);
  int updatebyprimarykeyselective(systemlog record);
  int updatebyprimarykey(systemlog record);
}

编写service层

package com.gcx.service;
import com.gcx.entity.systemlog;
public interface systemlogservice {
  int deletesystemlog(string id);
  int insert(systemlog record);
  
  int inserttest(systemlog record);
  systemlog selectsystemlog(string id);
  
  int updatesystemlog(systemlog record);
}

编写service实现类serviceimpl

package com.gcx.service.impl;
import javax.annotation.resource;
import org.springframework.stereotype.service;
import com.gcx.annotation.log;
import com.gcx.dao.systemlogmapper;
import com.gcx.entity.systemlog;
import com.gcx.service.systemlogservice;
@service("systemlogservice")
public class systemlogserviceimpl implements systemlogservice {
  @resource
  private systemlogmapper systemlogmapper;
  
  @override
  public int deletesystemlog(string id) {
    
    return systemlogmapper.deletebyprimarykey(id);
  }
  @override
  
  public int insert(systemlog record) {
    
    return systemlogmapper.insertselective(record);
  }
  @override
  public systemlog selectsystemlog(string id) {
    
    return systemlogmapper.selectbyprimarykey(id);
  }
  @override
  public int updatesystemlog(systemlog record) {
    
    return systemlogmapper.updatebyprimarykeyselective(record);
  }
  @override
  public int inserttest(systemlog record) {
    
    return systemlogmapper.insert(record);
  }
}

到这里基本程序编写完毕

下面开始自定义注解

package com.gcx.annotation;
import java.lang.annotation.*;
@target({elementtype.parameter, elementtype.method}) 
@retention(retentionpolicy.runtime) 
@documented 
public @interface log {
  /** 要执行的操作类型比如:add操作 **/ 
  public string operationtype() default ""; 
   
  /** 要执行的具体操作比如:添加用户 **/ 
  public string operationname() default "";
}

下面编写切面

package com.gcx.annotation;
import java.lang.reflect.method;
import java.util.date;
import java.util.uuid;
import javax.annotation.resource;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpsession;
import org.aspectj.lang.joinpoint;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.after;
import org.aspectj.lang.annotation.afterreturning;
import org.aspectj.lang.annotation.afterthrowing;
import org.aspectj.lang.annotation.around;
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 com.gcx.entity.systemlog;
import com.gcx.entity.user;
import com.gcx.service.systemlogservice;
import com.gcx.util.jsonutil;
/**
 * @author 杨建 
 * @e-mail: email
 * @version 创建时间:2015-10-19 下午4:29:05
 * @desc 切点类 
 */
@aspect
@component
public class systemlogaspect {
  //注入service用于把日志保存数据库 
  @resource //这里我用resource注解,一般用的是@autowired,他们的区别如有时间我会在后面的博客中来写
  private systemlogservice systemlogservice; 
  
  private static final logger logger = loggerfactory.getlogger(systemlogaspect. class); 
  
  //controller层切点 
  @pointcut("execution (* com.gcx.controller..*.*(..))") 
  public void controlleraspect() { 
  } 
  
  /** 
   * 前置通知 用于拦截controller层记录用户的操作 
   * 
   * @param joinpoint 切点 
   */ 
  @before("controlleraspect()")
  public void dobefore(joinpoint joinpoint) {
    system.out.println("==========执行controller前置通知===============");
    if(logger.isinfoenabled()){
      logger.info("before " + joinpoint);
    }
  }  
  
  //配置controller环绕通知,使用在方法aspect()上注册的切入点
   @around("controlleraspect()")
   public void around(joinpoint joinpoint){
     system.out.println("==========开始执行controller环绕通知===============");
     long start = system.currenttimemillis();
     try {
       ((proceedingjoinpoint) joinpoint).proceed();
       long end = system.currenttimemillis();
       if(logger.isinfoenabled()){
         logger.info("around " + joinpoint + "\tuse time : " + (end - start) + " ms!");
       }
       system.out.println("==========结束执行controller环绕通知===============");
     } catch (throwable e) {
       long end = system.currenttimemillis();
       if(logger.isinfoenabled()){
         logger.info("around " + joinpoint + "\tuse time : " + (end - start) + " ms with exception : " + e.getmessage());
       }
     }
   }
  
  /** 
   * 后置通知 用于拦截controller层记录用户的操作 
   * 
   * @param joinpoint 切点 
   */ 
  @after("controlleraspect()") 
  public void after(joinpoint joinpoint) { 
 
    /* httpservletrequest request = ((servletrequestattributes) requestcontextholder.getrequestattributes()).getrequest(); 
    httpsession session = request.getsession(); */
    //读取session中的用户 
    // user user = (user) session.getattribute("user"); 
    //请求的ip 
    //string ip = request.getremoteaddr();
    user user = new user();
    user.setid(1);
    user.setname("张三");
    string ip = "127.0.0.1";
     try { 
      
      string targetname = joinpoint.gettarget().getclass().getname(); 
      string methodname = joinpoint.getsignature().getname(); 
      object[] arguments = joinpoint.getargs(); 
      class targetclass = class.forname(targetname); 
      method[] methods = targetclass.getmethods();
      string operationtype = "";
      string operationname = "";
       for (method method : methods) { 
         if (method.getname().equals(methodname)) { 
          class[] clazzs = method.getparametertypes(); 
           if (clazzs.length == arguments.length) { 
             operationtype = method.getannotation(log.class).operationtype();
             operationname = method.getannotation(log.class).operationname();
             break; 
          } 
        } 
      }
      //*========控制台输出=========*// 
      system.out.println("=====controller后置通知开始====="); 
      system.out.println("请求方法:" + (joinpoint.gettarget().getclass().getname() + "." + joinpoint.getsignature().getname() + "()")+"."+operationtype); 
      system.out.println("方法描述:" + operationname); 
      system.out.println("请求人:" + user.getname()); 
      system.out.println("请求ip:" + ip); 
      //*========数据库日志=========*// 
      systemlog log = new systemlog(); 
      log.setid(uuid.randomuuid().tostring());
      log.setdescription(operationname); 
      log.setmethod((joinpoint.gettarget().getclass().getname() + "." + joinpoint.getsignature().getname() + "()")+"."+operationtype); 
      log.setlogtype((long)0); 
      log.setrequestip(ip); 
      log.setexceptioncode( null); 
      log.setexceptiondetail( null); 
      log.setparams( null); 
      log.setcreateby(user.getname()); 
      log.setcreatedate(new date()); 
      //保存数据库 
      systemlogservice.insert(log); 
      system.out.println("=====controller后置通知结束====="); 
    } catch (exception e) { 
      //记录本地异常日志 
      logger.error("==后置通知异常=="); 
      logger.error("异常信息:{}", e.getmessage()); 
    } 
  } 
  
  //配置后置返回通知,使用在方法aspect()上注册的切入点
   @afterreturning("controlleraspect()")
   public void afterreturn(joinpoint joinpoint){
     system.out.println("=====执行controller后置返回通知====="); 
       if(logger.isinfoenabled()){
         logger.info("afterreturn " + joinpoint);
       }
   }
  
  /** 
   * 异常通知 用于拦截记录异常日志 
   * 
   * @param joinpoint 
   * @param e 
   */ 
   @afterthrowing(pointcut = "controlleraspect()", throwing="e") 
   public void doafterthrowing(joinpoint joinpoint, throwable e) { 
    /*httpservletrequest request = ((servletrequestattributes) requestcontextholder.getrequestattributes()).getrequest(); 
    httpsession session = request.getsession(); 
    //读取session中的用户 
    user user = (user) session.getattribute(webconstants.current_user); 
    //获取请求ip 
    string ip = request.getremoteaddr(); */ 
    //获取用户请求方法的参数并序列化为json格式字符串 
    
    user user = new user();
    user.setid(1);
    user.setname("张三");
    string ip = "127.0.0.1";
    
    string params = ""; 
     if (joinpoint.getargs() != null && joinpoint.getargs().length > 0) { 
       for ( int i = 0; i < joinpoint.getargs().length; i++) { 
        params += jsonutil.getjsonstr(joinpoint.getargs()[i]) + ";"; 
      } 
    } 
     try { 
       
       string targetname = joinpoint.gettarget().getclass().getname(); 
       string methodname = joinpoint.getsignature().getname(); 
       object[] arguments = joinpoint.getargs(); 
       class targetclass = class.forname(targetname); 
       method[] methods = targetclass.getmethods();
       string operationtype = "";
       string operationname = "";
       for (method method : methods) { 
         if (method.getname().equals(methodname)) { 
           class[] clazzs = method.getparametertypes(); 
           if (clazzs.length == arguments.length) { 
             operationtype = method.getannotation(log.class).operationtype();
             operationname = method.getannotation(log.class).operationname();
             break; 
           } 
         } 
       }
       /*========控制台输出=========*/ 
      system.out.println("=====异常通知开始====="); 
      system.out.println("异常代码:" + e.getclass().getname()); 
      system.out.println("异常信息:" + e.getmessage()); 
      system.out.println("异常方法:" + (joinpoint.gettarget().getclass().getname() + "." + joinpoint.getsignature().getname() + "()")+"."+operationtype); 
      system.out.println("方法描述:" + operationname); 
      system.out.println("请求人:" + user.getname()); 
      system.out.println("请求ip:" + ip); 
      system.out.println("请求参数:" + params); 
        /*==========数据库日志=========*/ 
      systemlog log = new systemlog();
      log.setid(uuid.randomuuid().tostring());
      log.setdescription(operationname); 
      log.setexceptioncode(e.getclass().getname()); 
      log.setlogtype((long)1); 
      log.setexceptiondetail(e.getmessage()); 
      log.setmethod((joinpoint.gettarget().getclass().getname() + "." + joinpoint.getsignature().getname() + "()")); 
      log.setparams(params); 
      log.setcreateby(user.getname()); 
      log.setcreatedate(new date()); 
      log.setrequestip(ip); 
      //保存数据库 
      systemlogservice.insert(log); 
      system.out.println("=====异常通知结束====="); 
    } catch (exception ex) { 
      //记录本地异常日志 
      logger.error("==异常通知异常=="); 
      logger.error("异常信息:{}", ex.getmessage()); 
    } 
     /*==========记录本地异常日志==========*/ 
    logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinpoint.gettarget().getclass().getname() + joinpoint.getsignature().getname(), e.getclass().getname(), e.getmessage(), params); 
 
  } 
  
}

我这里写的比较全,前置通知,环绕通知,后置通知,异常通知,后置饭后通知,都写上了,在我们实际编写中不写全也没事,我习惯上把记录日志的逻辑写在后置通知里面,我看网上也有些在前置通知里面的,但我感觉写在后置通知里比较好。

下面开始在controller中加入自定义的注解!!

package com.gcx.controller;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import com.gcx.annotation.log;
import com.gcx.service.userservice;
@controller
@requestmapping("usercontroller")
public class usercontroller {
  @autowired
  private userservice userservice;
  
  @requestmapping("testaop")
  @log(operationtype="add操作:",operationname="添加用户") 
  public void testaop(string username,string password){    
    userservice.adduser(username, password);
  }
}

下面编写测试类

@test
  public void testaop1(){
    //启动spring容器    
    applicationcontext ctx = new classpathxmlapplicationcontext(new string[]{"classpath:applicationcontext-mvc.xml","classpath:applicationcontext-datasource.xml"});
    //获取service或controller组件
    usercontroller usercontroller = (usercontroller) ctx.getbean("usercontroller");
    usercontroller.testaop("zhangsan", "123456");
  }

spring AOP自定义注解方式实现日志管理的实例讲解

数据库数据:

spring AOP自定义注解方式实现日志管理的实例讲解

我原本想写两个切点,一个是service层,一个是controller层,service层是用来记录异常信息的日志,而controller层的是用来记录功能的日志,运行结果如下。 spring AOP自定义注解方式实现日志管理的实例讲解

这样做的话不知道在实际的项目中运行效率好不好,在这里请看到博客的大牛给点建议!!

以上这篇spring aop自定义注解方式实现日志管理的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。