weixin_46546553 2022-08-10 09:42 采纳率: 66.7%
浏览 300
已结题

SpringAOP获取实体类参数中的某个属性

用SpringAOP实现对日志的管理

我刚开始用这种方法可以做到插入,但是别人说我要是有表结构扩展到200张,是不是要有200个else if

if(operationLog!=null) {
            //注入信息
            log.setLogCat(operationLog.operationType().getValue());
            log.setLogContent(operationLog.operationContent().getValue());
        }
        //获取参数名称
        String[] paramName = signature.getParameterNames();
        //获取参数的值
        Object json = JSON.toJSON(joinPoint.getArgs());
        //判断参数是属于哪个实体类
        if("upgradeRecord".equals(paramName[0])) {
            UpgradeRecord upgradeRecord = JSON.parseObject(json.toString(), UpgradeRecord.class);
            log.setLogHotel(upgradeRecord.getUpgradeHotel());

        }
        else if("hotelInfo".equals(paramName[0])){
            HotelInfo hotelInfo =JSON.parseObject(json.toString(), HotelInfo.class);
            log.setLogHotel(hotelInfo.getDescript());
        }
        //日志记录保存
        if(log!=null){
        upgradeOperationLogMapper.insert(log);
        }


 然后我改成下面这种方式

public class LogAspect {
    @Autowired
    private UpgradeOperationLogService upgradeOperationLogService;
    /**
     * 此处的切点是注解的方式
     */
    @Pointcut("@annotation(org.foxhis.operation.maintenance.management.config.annotation.OperationLog)")
    private void controllerAspect() {
    }
    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint  joinPoint)throws Throwable{
        UpgradeOperationLog log = new UpgradeOperationLog();
        Object result = null;
        try {
            result = joinPoint.proceed();
            // 获取operationLog注解
            OperationLog operationLog = getAnnotation(joinPoint);
            // 封装Log对象
            if(operationLog!=null) {
                log.setLogCat(operationLog.operationType().getValue());
                log.setLogContent(operationLog.operationContent().getValue());
            }
            Object param = getParams(joinPoint);
            LinkedHashMap linkedHashMap = (LinkedHashMap)param;
            Object info = linkedHashMap.get(0);
            System.out.println("info=========》"+info);
            System.out.println("获取参数=========》"+param);
            String hotel = JSON.toJSON(linkedHashMap.get("upgradeHotel")).toString();
            System.out.println("hotel=========》"+hotel);
            log.setLogHotel(hotel);
            upgradeOperationLogService.saveUpgradeOperationLog(log);
        } catch (Throwable e) {
            throw new Throwable(e);
        }finally {
        }
        return result;
}
/**
     * 获取参数
     * @param joinPoint
     * @return Object
     */
    private Object getParams(ProceedingJoinPoint joinPoint) {
        // 参数名
        String[] paramNames = getMethodSignature(joinPoint).getParameterNames();
        // 参数值
        Object[] paramValues = joinPoint.getArgs();
        // 存储参数
        Map<String, Object> params = new LinkedHashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];
            // MultipartFile对象以文件名作为参数值
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();
            }
            params.put(paramNames[i], value);
        }
        return params;
    }

    /**
     * 获取方法签名
     * @param joinPoint
     * @return MethodSignature
     */
    private MethodSignature getMethodSignature(ProceedingJoinPoint joinPoint) {
        return (MethodSignature) joinPoint.getSignature();
    }
    /**
     * 获取方法上的注解
     * @param joinPoint
     * @return OperationLog
     */
    private OperationLog getAnnotation(ProceedingJoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        return method.getAnnotation(OperationLog.class);
    }

但是报错了

 info=========》null
获取参数=========》{upgradeRecord=UpgradeRecord(id=618bbd2475b6d0989e93bf3f6a5dbcc3, upgradeHotel=北京大酒店, upgradeApplicant=zjh, upgradeApplyRemark=你好, currentHotelidVersion=XMS2022, upgradeApplyVersion=XMS2022, upgradeApplyToAppointmentTime=Fri Aug 26 00:00:00 CST 2022, upgradeApplyStatus=R)}
2022-08-10 09:28:42.003 ERROR 18320 --- [nio-9856-exec-9] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/maintenance] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Invocation failure
Controller [org.foxhis.operation.maintenance.management.controller.UpgradeRecordController]
Method [org.foxhis.operation.maintenance.management.vo.Result org.foxhis.operation.maintenance.management.controller.UpgradeRecordController.savePendingUsers(org.foxhis.operation.maintenance.management.entity.UpgradeRecord)] with argument values:
 [0] [type=org.foxhis.operation.maintenance.management.entity.UpgradeRecord] [value=UpgradeRecord(id=618bbd2475b6d0989e93bf3f6a5dbcc3, upgradeHotel=北京大酒店, upgradeApplicant=zjh, upgradeApplyRemark=你好, currentHotelidVersion=XMS2022, upgradeApplyVersion=XMS2022, upgradeApplyToAppointmentTime=Fri Aug 26 00:00:00 CST 2022, upgradeApplyStatus=R)] ] with root cause

java.lang.NullPointerException: null
    at org.foxhis.operation.maintenance.management.config.aop.LogAspect.doAround(LogAspect.java:53) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_321]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_321]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_321]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_321]
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.foxhis.operation.maintenance.management.controller.UpgradeRecordController$$EnhancerBySpringCGLIB$$3f54cba3.savePendingUsers(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_321]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_321]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_321]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_321]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.41.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.41.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:114) ~[druid-1.2.11.jar:1.2.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_321]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_321]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at java.lang.Thread.run(Thread.java:750) [na:1.8.0_321]

求指教

  • 写回答

4条回答 默认 最新

  • 运笔如飞 2022-08-10 10:05
    关注

    你这种方式拿到的参数名和参数值其实是存在一种关系的,比如说 paramsNames[1]对应的 是 key1,那么paramsValues[1]对应的就是value1,他们是一一对应的,所以你可以不用 instanseof 直接 new 一个 hashmap 然后 put(key,values.get(key.indexof(key))),就行了,我给你个示例:

    List<Object> values = Arrays.asList(joinPoint.getArgs());
            String[] parameterNames = ((MethodSignature) joinPoint
                    .getSignature())
                    .getParameterNames();
            List<String> keys = Arrays.asList(parameterNames);
            return keys.stream().collect(HashMap::new, (k, v) -> k
                    .put(v, values.get(keys.indexOf(v))), HashMap::putAll);
    

    或者你可以直接从request取值,这样取出来的就直接是 key-value形式的,如下:

    HttpServletRequest request = getHttpServletAttributes().getRequest();
            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, List<String>> hashMap = new HashMap<>();
            for (Map.Entry<String,String[]> entry : parameterMap.entrySet()) {
                hashMap.put(entry.getKey(), Arrays.asList(entry.getValue()));
            }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 8月18日
  • 已采纳回答 8月10日
  • 创建了问题 8月10日

悬赏问题

  • ¥15 soildworks装配体的尺寸问题
  • ¥100 有偿寻云闪付SDK转URL技术
  • ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
  • ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑