基于切面实现公共自定义注解

88 阅读1分钟

methodext-spring-boot-starter

前言

实现一个中间件,可以加入到其他方法的自定义注解配置和拦截操作,可以在调用现有方法时优先执行我们自己定义的配置方法。

  • 使用自定义注解和切面技术,拦截和执行新增的扩展方法。
  • 拦截后到方法后,就可以执行此方法内容。需要注意,扩展的方法需要有一定的约束,例如相同的入参信息,以及固定的出参类型。

GIT地址:gitee.com/yixiaodai1/…

具体使用方法:

  • DoMethodExtAfterPoint 执行返回后切点注解
  • DoMethodExtAllPoint 执行方法前中后切点注解,无返回信息
  • DoMethodExtAroundPoint 执行方法前切点注解,自定义返回信息 默认返回boolean 执行完后 返回 true 则继续执行 false 返回returnJson自定义异常信息
public class GoodsService{

    @DoMethodExtAround(className = "chainThirdRecordServiceImpl" ,method = "aroundText", returnJson = "测试环绕拦截异常信息")
    public Object text1(Object obj) {
        //具体的业务逻辑
    }

    @DoMethodExtAfterPoint(className = "chainThirdRecordServiceImpl" ,method = "afterText")
    public Object text2(Object obj) {
        //具体的业务逻辑
    }

}

在指定的className类中,实现自定义的执行方法

@Service
public class ChainThirdRecordServiceImpl {
    /**
     * 环绕拦截
     * @param args 方法参数 
     * 默认返回是boolean
     */
    public boolean aroundText(Object[] args) {
        //具体的业务实现
       
    }
    
    /**
     * 后置拦截
     * @param args 方法参数
     */
    public void afterText(Object[] args) {
        //具体的业务实现
        
    }
}