当前位置: 代码网 > it编程>编程语言>Java > Java中Spring使用AOP获取值类型实现过程

Java中Spring使用AOP获取值类型实现过程

2026年09月11日 Java 我要评论
一、aop简介1.aop简介aop为aspect oriented programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。这种在运行时,动

一、aop简介

1.aop简介

aop为aspect oriented programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。

这种在运行时,动态地将代码切入到类的指定方法或指定位置上的编程思想就是面向切面的编程。

利用aop可以将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来作为公共部分,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

2.aop作用

日志记录,性能统计,安全控制,事务处理,异常处理等等。

在面向切面编程aop的思想里面,核心业务和切面通用功能(例如事务处理、日志管理、权限控制等)分别独立进行开发,然后把切面功能和核心业务功能 “编织” 在一起,这就叫aop。

这种思想有利于减少系统的重复代码,降低模块间的耦合度,并有利于未来的可拓展性和可维护性。

3.aop相关术语

通知(advice)

通知描述了切面要完成的工作以及何时执行。

比如我们的日志切面需要记录每个接口调用时长,就需要在接口调用前后分别记录当前时间,再取差值。

  • 前置通知(before):在目标方法调用前调用通知功能;
  • 后置通知(after):在目标方法调用之后调用通知功能,不关心方法的返回结果;
  • 返回通知(afterreturning):在目标方法成功执行之后调用通知功能;
  • 异常通知(afterthrowing):在目标方法抛出异常后调用通知功能;
  • 环绕通知(around):通知包裹了目标方法,在目标方法调用之前和之后执行自定义的行为。

切点(pointcut)

切点定义了通知功能被应用的范围。

比如日志切面的应用范围就是所有接口,即所有controller层的接口方法。

切面(aspect)

切面是通知和切点的结合,定义了何时、何地应用通知功能。

引入(introduction)

在无需修改现有类的情况下,向现有的类添加新方法或属性。

织入(weaving)

把切面应用到目标对象并创建新的代理对象的过程。

连接点(joinpoint)

通知功能被应用的时机。

比如接口方法被调用的时候就是日志切面的连接点。

3.1 jointpoint和proceedingjoinpoint

jointpoint是程序运行过程中可识别的连接点,这个点可以用来作为aop切入点。

jointpoint对象则包含了和切入相关的很多信息,比如切入点的方法,参数、注解、对象和属性等。

我们可以通过反射的方式获取这些点的状态和信息,用于追踪tracing和记录logging应用信息。

(1)jointpoint

通过jpointpoint对象可以获取到下面信息

# 返回目标对象,即被代理的对象
object gettarget();
 
# 返回切入点的参数
object[] getargs();
 
# 返回切入点的signature
signature getsignature();
 
# 返回切入的类型,比如method-call,field-get等等,感觉不重要 
 string getkind();

(2)proceedingjoinpoint

proceedingjoinpoint 继承了 joinpoint。

是在joinpoint的基础上暴露出 proceed 这个方法。proceed很重要,这个是aop代理链执行的方法。

环绕通知=前置+目标方法执行+后置通知,proceed方法就是用于启动目标方法执行的。

暴露出这个方法:

就能支持 aop:around 这种切面(而其他的几种切面只需要用到joinpoint,这也是环绕通知和前置、后置通知方法的一个最大区别。这跟切面类型有关)。

能决定是否走代理链还是走自己拦截的其他逻辑。

proceedingjoinpoint可以获取切入点的信息:

  • 切入点的方法名字及其参数
  • 切入点方法标注的注解对象(通过该对象可以获取注解信息)
  • 切入点目标对象(可以通过反射获取对象的类名,属性和方法名)
//获取切入点方法的名字,getsignature());是获取到这样的信息 :修饰符+ 包名+组件名(类名) +方法名
string methodname = joinpoint.getsignature().getname()
 
//获取方法的参数,这里返回的是切入点方法的参数列表
object[] args = joinpoint.getargs();
 
//获取方法上的注解
signature signature = joinpoint.getsignature();
methodsignature methodsignature = (methodsignature) signature;
method method = methodsignature.getmethod();
if (method != null)
{
   xxxxxx annoobj= method.getannotation(xxxxxx.class);
}
 
//获取切入点所在目标对象
object targetobj =joinpoint.gettarget();
//可以发挥反射的功能获取关于类的任何信息,例如获取类名如下
string classname = joinpoint.gettarget().getclass().getname();

3.2 proceedingjoinpoint获取返回类型、参数名称/值等一些常用方法

3.2.1、参数值

object[] args = joinpoint.getargs();

3.2. 2、参数名称

signature signature = joinpoint.getsignature();
if (signature instanceof methodsignature) {
    methodsignature methodsignature = (methodsignature) signature;
    string[] properties = methodsignature.getparameternames();
}

3.2.3、返回类型

signature signature = joinpoint.getsignature();
if (signature instanceof methodsignature) {
    methodsignature methodsignature = (methodsignature) signature;
    // 被切的方法
    method method = methodsignature.getmethod();
    // 返回类型
    class<?> methodreturntype = method.getreturntype();
    // 实例化
    object o = methodreturntype.newinstance();
}
 

3.2.4、全限定类名

signature signature = joinpoint.getsignature();
signature.getdeclaringtypename()

3.2.5、方法名

signature signature = joinpoint.getsignature();
signature.getname()

4.aop相关注解

spring中使用注解创建切面:

  • @aspect:用于定义切面
  • @before:通知方法会在目标方法调用之前执行
  • @after:通知方法会在目标方法返回或抛出异常后执行
  • @afterreturning:通知方法会在目标方法返回后执行
  • @afterthrowing:通知方法会在目标方法抛出异常后执行
  • @around:通知方法会将目标方法封装起来
  • @pointcut:定义切点表达式
  • 切点表达式:指定了通知被应用的范围,表达式格式:
execution(方法修饰符 返回类型 方法所属的包.类名.方法名称(方法参数)
//com.hs.demo.controller包中所有类的public方法都应用切面里的通知
execution(public * com.hs.demo.controller.*.*(..))
//com.hs.demo.service包及其子包下所有类中的所有方法都应用切面里的通知
execution(* com.hs.demo.service..*.*(..))
//com.hs.demo.service.employeeservice类中的所有方法都应用切面里的通知
execution(* com.hs.demo.service.employeeservice.*(..))

(1)@pointcut定义切入点,有以下2种方式:

方式一:设置为注解@logfilter标记的方法,有标记注解的方法触发该aop,没有标记就没有。

@aspect
@component
public class logfilter1aspect {
	@pointcut(value = "@annotation(com.hs.aop.annotation.logfilter)")
	public void pointcut(){
	
	}
}

方式二:采用表达式批量添加切入点,如下方法,表示aopcontroller下的所有public方法都添加logfilter1切面。

@pointcut(value = "execution(public * com.train.aop.controller.aopcontroller.*(..))")
public void pointcut(){
 
}

@around环绕通知

@around集成了@before、@afterreturing、@afterthrowing、@after四大通知。

需要注意的是:

他和其他四大通知注解最大的不同是需要手动进行接口内方法的反射后才能执行接口中的方法,换言之,@around其实就是一个动态代理。

   /**
	 * 环绕通知是spring框架为我们提供的一种可以在代码中手动控制增强部分什么时候执行的方式。
	 *
	 */
	public void aroundpringlog(proceedingjoinpoint pjp)
   {
      //拿到目标方法的方法签名
       signature signature = pjp.getsignature();
      //获取方法名
      string name = signature.getname();
 
	  try {
			//@before
			system.out.println("【环绕前置通知】【"+name+"方法开始】");
            //这句相当于method.invoke(obj,args),通过反射来执行接口中的方法
			proceed = pjp.proceed();
			//@afterreturning
			system.out.println("【环绕返回通知】【"+name+"方法返回,返回值:"+proceed+"】");
		} catch (exception e) {
			//@afterthrowing
			system.out.println("【环绕异常通知】【"+name+"方法异常,异常信息:"+e+"】");
		}
        finally{
			//@after
			system.out.println("【环绕后置通知】【"+name+"方法结束】");
		}
	}

​proceed = pjp.proceed(args)这条语句其实就是method.invoke,以前手写版的动态代理,也是method.invoke执行了,jdk才会利用反射 进行动态代理的操作,在spring的环绕通知里面,只有这条语句执行了,spring才会去切入到目标方法中。

二、为什么说环绕通知就是一个动态代理呢?

proceed = pjp.proceed(args)这条语句就是动态代理的开始,当我们把这条语句用try-catch包围起来的时候,在这条语句前面写的信息,就相当于前置通知,在它后面写的就相当于返回通知,在catch里面写的就相当于异常通知,在finally里写的就相当于后置通知。

1.引入依赖

<dependency>  
    <groupid>org.springframework.boot</groupid>  
    <artifactid>spring-boot-starter-aop</artifactid>  
</dependency>

2.自定义日志注解

package com.wondertek.center.aspect.annotation;

import java.lang.annotation.*;

/**
 * 定义操作日志注解
 */
@target(elementtype.method)
@retention(retentionpolicy.runtime)
@documented
public @interface loginfo
{
}

package com.wondertek.center.aspect;

import cn.hutool.core.collection.collectionutil;
import cn.hutool.json.jsonutil;
import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
import com.alibaba.fastjson.typereference;
import com.allcam.common.service.user.request.userinforequest;
import com.fasterxml.jackson.core.jsonprocessingexception;
import com.fasterxml.jackson.databind.objectmapper;
import com.google.common.collect.maps;
import com.wondertek.cache.util.redisutil;
import com.wondertek.center.aspect.annotation.loginfo;
import com.wondertek.center.client.customeruserservice;
import com.wondertek.center.constants.userconstants;
import com.wondertek.center.model.dto.accountinforequest;
import com.wondertek.center.model.dto.accountinforesponse;
import com.wondertek.center.model.dto.excutesendairesultdto;
import com.wondertek.center.model.entity.algorithmfactory;
import com.wondertek.center.model.vo.accountrolevo;
import com.wondertek.center.model.vo.excutesendairesultvo;
import com.wondertek.center.response.abilitylog;
import com.wondertek.center.service.abilitylogservice;
import com.wondertek.center.service.algorithmfactoryservice;
import com.wondertek.util.stringutil;
import com.wondertek.web.exception.bizerrorexception;
import com.wondertek.web.exception.enums.bizerrorcodeenum;
import com.wondertek.web.response.result;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.lang3.stringutils;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.signature;
import org.aspectj.lang.annotation.around;
import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.pointcut;
import org.aspectj.lang.reflect.methodsignature;
import org.springframework.http.httpstatus;
import org.springframework.stereotype.component;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.context.request.requestattributes;
import org.springframework.web.context.request.requestcontextholder;
import org.springframework.web.context.request.servletrequestattributes;

import javax.annotation.postconstruct;
import javax.annotation.resource;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
import java.lang.reflect.method;
import java.lang.reflect.parameter;
import java.util.*;

/**
 * @author xiaoxiangyuan
 */
@slf4j
@aspect
@component
@requiredargsconstructor
public class loginfoaspect {

    @resource
    private customeruserservice customeruserservice;
    @resource
    private redisutil redisutil;

    @resource
    private abilitylogservice abilitylogservice;

    @resource
    private algorithmfactoryservice algorithmfactoryservice;

    @postconstruct
    public void init() {
        log.info("loginfo()初始化完成");
    }
    // 定义一个切入点
    @pointcut("@annotation(com.wondertek.center.aspect.annotation.loginfo)")
    protected void loginfo() {
    }
    @around("loginfo()")
    public object recordoplog(proceedingjoinpoint joinpoint) throws throwable {
        boolean success = false;
        object result=null;
        try {
            result = joinpoint.proceed();
            success = true;
            return result;
        } finally {
            try {
                handlersavelog(joinpoint, success,result);
            } catch (exception e) {
                log.error("record op log failed.", e);
            }
        }

    }


    private void handlersavelog(proceedingjoinpoint joinpoint, boolean success,object result) throws instantiationexception, illegalaccessexception {
        methodsignature signature = (methodsignature) joinpoint.getsignature();
        object parameter = getparameter(signature.getmethod(), joinpoint.getargs());
        string dto = jsonutil.tojsonstr(parameter);
        excutesendairesultdto excutesendairesultdto = json.parseobject(json.tojsonstring(parameter), excutesendairesultdto.class);
        savelog(result,excutesendairesultdto,dto);


    }

    private void savelog(object result, excutesendairesultdto excutesendairesultdto,string dto) {

        //string token = request.getheader("token");
        string token = excutesendairesultdto.gettoken();
        string roletype = "";
        string accountname = "";
        string realname = "";
        string userid = "";
        if (stringutils.isnotblank(token)) {
            //管理员显示全部,普通用户只显示普通用户
            accountinforesponse userinfo = getuserinfo(token);
            userid = string.valueof(userinfo.getid());
            accountname = userinfo.getaccountname();
            realname = userinfo.getrealname();
            list<accountrolevo> roles = userinfo.getroles();
            for (accountrolevo role : roles) {
                if (role.getrolename().contains("管理员")) {
                    roletype = "管理员";
                } else {
                    roletype = "普通用户";
                }

            }
        }


        //获取响应结果
        string bo = jsonutil.tojsonstr(result);
        result<list<excutesendairesultvo>> response = jsonobject.parseobject(bo, new typereference<result<list<excutesendairesultvo>>>() {
        });

        string responsestr = "";
        if (httpstatus.ok.value() == (response.getcode())) {
            if (collectionutil.isnotempty(response.getdata())) {
                list<excutesendairesultvo> data = response.getdata();
                responsestr = jsonutil.tojsonstr(data);

            }
        }
        string aicode = excutesendairesultdto.getaicode();
        algorithmfactory algorithmbyaicode = algorithmfactoryservice.getalgorithmbyaicode(aicode);
        //根据aicode获取算法相关信息
        abilitylog abilitylog = new abilitylog();
        abilitylog.setuserid(userid);
        abilitylog.setabilityurl(algorithmbyaicode.getinterfaceaddress());
        abilitylog.setartworkurl(excutesendairesultdto.getfileurl());
        abilitylog.setresponseresult(responsestr);
        abilitylog.setcalltype(excutesendairesultdto.gettype());
        abilitylog.setrolename(roletype);
        abilitylog.setusername(accountname);
        abilitylog.setabilityname(algorithmbyaicode.getalgorithmname());
        abilitylog.setcreatetime(new date());
        abilitylog.setupdatetime(new date());
        abilitylog.setaicode(aicode);
        abilitylog.setdtoparam(dto);
        abilitylogservice.insert(abilitylog);

        log.info("保存日志成功!对象信息为:{}", jsonutil.tojsonstr(abilitylog));

    }

    private accountinforesponse getuserinfo(string token) {
        if (stringutil.isempty(token)) {
            throw new bizerrorexception(bizerrorcodeenum.user_token_expired);
        }
        string rediskey = userconstants.get_user_id_by_token + ":" + token;
        object o = redisutil.get(rediskey);
        if (o == null) {
            throw new bizerrorexception(bizerrorcodeenum.user_token_expired);
        }
        long userid = long.valueof(string.valueof(o));
        accountinforequest inforequest = new accountinforequest();
        inforequest.setid(userid);
        result<accountinforesponse> result = customeruserservice.queryaccountinfo(inforequest);
        result.assertsuccess();
        accountinforesponse data = result.getdata();
        return data;
    }



    /**
     * 根据方法和传入的参数获取请求参数
     */
    private object getparameter(method method, object[] args)
    {
        list<object> arglist = new arraylist<>();
        parameter[] parameters = method.getparameters();
        for (int i = 0; i < parameters.length; i++) {
            //将requestbody注解修饰的参数作为请求参数
            requestbody requestbody = parameters[i].getannotation(requestbody.class);
            if (requestbody != null) {
                arglist.add(args[i]);
            }
            //将requestparam注解修饰的参数作为请求参数
            requestparam requestparam = parameters[i].getannotation(requestparam.class);
            if (requestparam != null) {
                map<string, object> map = new hashmap<>();
                string key = parameters[i].getname();
                if (!stringutils.isempty(requestparam.value())) {
                    key = requestparam.value();
                }
                map.put(key, args[i]);
                arglist.add(map);
            }
        }
        if (arglist.size() == 0) {
            return null;
        } else if (arglist.size() == 1) {
            return arglist.get(0);
        } else {
            return arglist;
        }
    }

}

3.在controller层使用注解

  @apioperation(value = "测试", notes = "测试")
  @loginfo()
  @postmapping(value = centerapi.excute_send_ai_result)
  public result excutesendairesult(
      @requestbody @validated excutesendairesultdto excutesendairesultdto) {
    return new result(this.algorithmfactoryservice.excutesendairesult(excutesendairesultdto));
  }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com