基于spring@aspect注解的aop实现

第一步:编写切面类

package com.dascom.hawk.app.web.tool;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
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.springframework.stereotype.Component;

@Aspect
@Component
public class AnnotationAspectJ {

    //定义切面("execution(* com.dascom.common.aop.*.*(..)))
    //当前配置的意思是所有添加了SuiteMessage的注解的方法作为切点
    @Pointcut("@annotation(com.dascom.common.annotation.SuiteMessage)")
    public void logPointCut() {
    }
    
    //前置通知
    @Before("logPointCut()")
    public void before(JoinPoint point) {
        String calssName = point.getTarget().getClass().getName();
        String method = point.getSignature().getName();
        System.out.println(calssName + " : " + method);
    }
    
    //后置通知
    @After("logPointCut()")
    public void after(JoinPoint point) {
        String method = point.getSignature().getName();
        System.out.println(method + ": end----");
    }
    
    //环绕通知
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        System.out.println(time);
        return result;
    }
}

第二步:在spring的配置文件中添加注解扫描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.dascom.hawk.app.web.tool"></context:component-scan>
    <!-- 自动为切面方法中匹配的方法所在的类生成代理对象。
       proxy-target-class="true" 这个的作用是struts的控制类都基础的actionSupport,必须添加这个,不然会报错
     -->
    <aop:aspectj-autoproxy proxy-target-class="true" />
    
</beans>

第三步:搞定。爽歪歪~~~

转载于:https://www.cnblogs.com/Mustr/p/9372038.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值