<快速入门>,工作中使用AOP

本文通过一个实例介绍了如何使用AOP(面向切面编程)来简化开发,实现接口调用时自动增加权值的功能。主要涉及三个关键部分:定义注解@Weight,切面类实现权值增加,以及在接口上应用注解。AOP的使用降低了代码复杂性,提高了代码复用性。
摘要由CSDN通过智能技术生成

使用AOP是为了降低我们的开发量,且直观,我只需要知道这个AOP是做什么的就够了。

拿一个较为常用例子讲解:

一.Weight权值)

这个AOP实现的是为接口提供自动增加权值,只要有对该接口的调用就会实现一次权值增加。

我们要了解它的实现只需要了解3个步骤:

①:interface - 接口

package com.seatrend.sign.aop;

import *;

@Retention(value = RetentionPolicy.RUNTIME)
public @interface Weight {
}

这里需要了解的是它的生命周期:Retention

②:aspect - 切面

package com.seatrend.sign.aspect;

import *;

@Aspect
@Component
public class Weight {

    //增加权值的sql
    @Autowired
    private Mapper Mapper;

    //接口的路径
    @Pointcut("execution(@com.seatrend.sign.aop.Weight * *(..))")
    private void method() {

    }
    
    //表示在接口实现后再调用这里的method
    @After("method()")
    public void increaseWeight() throws Exception {
        //获取我们接口参数,对该xh对应的数据权值进行运算
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String xh = request.getParameter("xh");
        Mapper.addOne(xh);
    }
}

这里我们还需要去了解的是:After、Before、Around 

③:request - 使用方式

@ApiImpliciParam(name = "xh", required = "true", dataType = "string")
@Weight
public void xxx(@RequestParam(value = "xh") String xh) {
    ...
}

直接放在接口上即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值