spring boot中使用AOP

spring boot 中使用AOP,需要先在pom.xml中添加依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

然后编写切面程序,例如:

@Aspect
@Component
public class HttpAspect {

    private static final Logger logger=LoggerFactory.getLogger(HttpAspect.class);

    //配置切点
    @Pointcut("execution(public * com.springboot.controller.GirlController.*(..))")
    public void log(){
    }

    //joinPoint用于获取域切入点方法有关的信息
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=requestAttributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURL());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getLocalAddr());
        //类方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringType()+"."+joinPoint.getSignature().getName());
        //方法参数
        logger.info("args={}",joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter(){
        logger.info("doAfter={}",2222222);
    }

    //得到response返回的数据,returning代表切入点方法返回的数据
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        logger.info("response={}",object.toString());
    }
}

需要在类上添加@Aspect注解表明这是一个切面,添加@Component注解是为了能够让spring的bean容器对齐进行管理,然后在对应的方法上添加需要表明什么时候执行切面的对应注解,如果需要获取切入点有关方法的信息,可以传入JoinPoint对象。要得到response响应的数据,参考上面@AfterReturning注解的使用。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值