SpingMvcAOP日志案例

91 阅读1分钟

导入坐标

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

编写SPring配置文件

<!--开启AOP注解支持,开启AspectJ 注解自动代理机制,扫描含有@Aspect的bean-->
    <aop:aspectj-autoproxy/>

定义日志类


@Data
@Alias("log")
@Component
public class SysLog {
    private int id;
    private Date visitTime;
    private String visitTimeStr;
    private String username;
    private String ip;
    private String url;
    private Long executionTime;
    private String method;
    
    
    public String getVisitTimeStr() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != visitTime) {
            visitTimeStr = format.format(visitTime);
        }
        return visitTimeStr;
    }
}

创建AOP包 和AOP类

@Component
@Aspect
public class SysLogAop {
    //日志对象
    @Resource
    private SysLog log;
    //请求对象
    @Resource
    private HttpServletRequest request;
    //日志持久层对象
    @Resource
    private SysLogDao logDao;
    /*前置通知:在controller方法执行之前调用*/
    @Before("execution(* com.yunhe.controller.*.*(..)) ")
    public void before(){
        //获取controller的的访问时间
        Date visitTime = new Date();
        log.setVisitTime(visitTime);
    }
    /*后置通知:在controller方法执行之后调用*/
    @After("execution(* com.yunhe.controller.*.*(..))")
    public void after(JoinPoint point){
        /**************************计算执行时间**********************/
        //获取一个controller方法执行完成的时间
        Date endTime = new Date();
        //计算controller请求处理的时间
        long executionTime = endTime.getTime() - log.getVisitTime().getTime();
        //设置到日志对象的属性中
        log.setExecutionTime(executionTime);
        /***********************获取访问的controller方法***************/
        String methodName = point.getSignature().getName();
        //方法所属类的反射对象
        Class cls = point.getTarget().getClass();
        //拼接类名和方法
        String methodStr = cls.getName()+"类中的:"+methodName;
        //设置到日志对象中
        log.setMethod(methodStr);
        /************************获取请求中ip和请求地址**************/
        String ip = request.getRemoteAddr();
        //判断如果是本机ip地址的"0:0:0:0:0:0:0:1" 形式,则转换成127.0.0.1
        ip = "0:0:0:0:0:0:0:1".equals(ip)?"127.0.0.1":ip;
        //设置到log
        log.setIp(ip);
        String url = request.getRequestURL().toString();
        //设置到log
        log.setUrl(url);
        /****************************获取当前访问资源的用户名称(获取Security上下文中共享的认证用户)****************************/
        //获取Security上下文对象
        SecurityContext context = SecurityContextHolder.getContext();
        //获取当前的(登录用户)认证用户
        User user =(User) context.getAuthentication().getPrincipal();
        String username = user.getUsername();
        //设置到log中
        log.setUsername(username);
        System.out.println(log);
        //调用dao层方法保存信息
        logDao.saveLog(log);
    }
}