springAOP进行自定义注解,用于方法的处理

2024-06-01 01:48

本文主要是介绍springAOP进行自定义注解,用于方法的处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文采用的spring boot进行配置

maven 引入

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

 

application.properties文件开启aop注解

spring.aop.auto = true;

 

自定义注解类

 

 

package com.kuaixin.crm.crm_tsale_kx_service.service.anno;import java.lang.annotation.*;/***自定义注解 拦截service*/@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceType {/*** 方法描述* @return*/String description()  default "";/*** 方法类型 0 表示不进行处理,1 表示进行处理* @return*/int type() default 0;/*** 类的元数据,用于指定需要转换为的目标格式* @return*/Class classType();
}

 

 

 

 

切点类

package com.kuaixin.crm.crm_tsale_kx_service.service.anno;import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;/*** Created by Administrator on 2017/8/31.* @desc 定义切点类,无论是前置通知还是后置通知、环绕通知以及异常通知,都需要在指定的方法上加上SystemServiceType注释就会生效* 还可以在通知中记录日志*/
@Component // 注册到Spring容器,必须加入这个注解
@Aspect // 该注解标示该类为切面类,切面是由通知和切点组成的。
public class SystemServiceTypeAspect {//注入Service用于把日志保存数据库/*  @Resourceprivate LogService logService;*///日志记录对象private final static Logger log = LogManager.getLogger(SystemServiceTypeAspect.class);//Service层切点@Pointcut("@annotation(com.kuaixin.crm.crm_tsale_kx_service.service.anno.SystemServiceType)")public  void serviceAspect() {}//controller层切点 com.kuaixin.crm.crm_tsale_kx_service.service.anno.SystemServiceType可以指定另外定义的注释接口@Pointcut("@annotation(com.kuaixin.crm.crm_tsale_kx_service.service.anno.SystemServiceType)")public  void controllerAspect() {}/***对某个方法返回的结果进行处理后,如将entity转换为与前端交互的vo*/@Around(value = "serviceAspect()")public Object aroundProcess(ProceedingJoinPoint pjp) throws Throwable {Object retVal = pjp.proceed();//*==========记录本地异常日志==========*//*//logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);//需要转换为的vo对象ClassClass vClass = getClassByAnno(pjp);//数组或集合对象if(retVal.getClass().isArray()||retVal instanceof List){List list = new ArrayList<>();for(Object origin:(List)retVal){Object dest = vClass.newInstance();BeanUtils.copyProperties(dest,origin);list.add(dest);}return list;}//单个对象Object dest = vClass.newInstance();BeanUtils.copyProperties(dest,retVal);return dest;}/*** 前置通知** @param joinPoint 切点*/@Before("serviceAspect()")public  void doBefore(JoinPoint joinPoint) {//获得http请求HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();HttpSession session = request.getSession();//读取session中的用户//User user = (User) session.getAttribute(WebConstants.CURRENT_USER);//请求的IPString ip = request.getRemoteAddr();try {String desc = getServiceMthodDescription(joinPoint);log.info("getServiceMthodDescription:"+desc);} catch (Exception e) {log.error("aop处理异常:", e);}}/*** 后置通知** @param joinPoint 切点*/@After("serviceAspect()")public  void doAfter(JoinPoint joinPoint) {try {String desc = getServiceMthodDescription(joinPoint);log.info("getServiceMthodDescription:"+desc);} catch (Exception e) {log.error("aop处理异常:", e);}}/*** 异常通知 用于拦截service层记录异常日志** @param joinPoint* @param e*/@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();HttpSession session = request.getSession();//读取session中的用户// User user = (User) session.getAttribute(WebConstants.CURRENT_USER);//获取请求ipString ip = request.getRemoteAddr();//获取用户请求方法的参数并序列化为JSON格式字符串String params = "";if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {}//日志记录操作............../*    Log log = SpringContextHolder.getBean("logxx");log.setDescription(getControllerMethodDescription(joinPoint));log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));log.setType("0");log.setRequestIp(ip);log.setExceptionCode( null);log.setExceptionDetail( null);log.setParams( null);log.setCreateBy(user);log.setCreateDate(DateUtil.getCurrentDate());//保存数据库logService.add(log);*/}/*** 获取注解中对方法的描述信息type等 用于service层注解k** @param joinPoint 切点* @return 方法描述* @throws Exception*/public static String getServiceMthodDescription(JoinPoint joinPoint)throws Exception {String targetName = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();Object[] arguments = joinPoint.getArgs();Class targetClass = Class.forName(targetName);Method[] methods = targetClass.getMethods();String description = "";for (Method method : methods) {if (method.getName().equals(methodName)) {Class[] clazzs = method.getParameterTypes();if (clazzs.length == arguments.length) {SystemServiceType serviceType = method.getAnnotation(SystemServiceType.class);//得到对应的方法结果Class clazz = serviceType.classType();int type = serviceType.type();description = serviceType.description();log.info("type:" + type);break;}}}return description;}/**** 获取aop拦截到的方法注解的Class* @param pjp* @return*/public static Class getClassByAnno(ProceedingJoinPoint pjp){Class<?> aClass = pjp.getTarget().getClass();Method[] methods = aClass.getMethods();for (Method method : methods) {Annotation[] annotations = method.getAnnotations();for (Annotation annotation : annotations) {// 获取注解的具体类型Class<? extends Annotation> annotationType = annotation.annotationType();//比较当前方法注解是否是SystemServiceType注解if (SystemServiceType.class == annotationType) {log.info("方法:" + method.getName() + "()\t" + SystemServiceType.class.getName());SystemServiceType serviceType = method.getAnnotation(SystemServiceType.class);//得到对应的方法结果Class clazz = serviceType.classType();int type = serviceType.type();String desc = serviceType.description();return clazz;}}}return null;}}Object retVal = pjp.proceed();//*==========记录本地异常日志==========*//*//logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);//需要转换为的vo对象ClassClass vClass = getClassByAnno(pjp);//数组或集合对象if(retVal.getClass().isArray()||retVal instanceof List){List list = new ArrayList<>();for(Object origin:(List)retVal){Object dest = vClass.newInstance();BeanUtils.copyProperties(dest,origin);list.add(dest);}return list;}//单个对象Object dest = vClass.newInstance();BeanUtils.copyProperties(dest,retVal);return dest;}/*** 前置通知** @param joinPoint 切点*/@Before("serviceAspect()")public  void doBefore(JoinPoint joinPoint) {//获得http请求HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();HttpSession session = request.getSession();//读取session中的用户//User user = (User) session.getAttribute(WebConstants.CURRENT_USER);//请求的IPString ip = request.getRemoteAddr();try {String desc = getServiceMthodDescription(joinPoint);log.info("getServiceMthodDescription:"+desc);} catch (Exception e) {log.error("aop处理异常:", e);}}/*** 后置通知** @param joinPoint 切点*/@After("serviceAspect()")public  void doAfter(JoinPoint joinPoint) {try {String desc = getServiceMthodDescription(joinPoint);log.info("getServiceMthodDescription:"+desc);} catch (Exception e) {log.error("aop处理异常:", e);}}/*** 异常通知 用于拦截service层记录异常日志** @param joinPoint* @param e*/@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();HttpSession session = request.getSession();//读取session中的用户// User user = (User) session.getAttribute(WebConstants.CURRENT_USER);//获取请求ipString ip = request.getRemoteAddr();//获取用户请求方法的参数并序列化为JSON格式字符串String params = "";if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {}//日志记录操作............../*    Log log = SpringContextHolder.getBean("logxx");log.setDescription(getControllerMethodDescription(joinPoint));log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));log.setType("0");log.setRequestIp(ip);log.setExceptionCode( null);log.setExceptionDetail( null);log.setParams( null);log.setCreateBy(user);log.setCreateDate(DateUtil.getCurrentDate());//保存数据库logService.add(log);*/}/*** 获取注解中对方法的描述信息type等 用于service层注解k** @param joinPoint 切点* @return 方法描述* @throws Exception*/public static String getServiceMthodDescription(JoinPoint joinPoint)throws Exception {String targetName = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();Object[] arguments = joinPoint.getArgs();Class targetClass = Class.forName(targetName);Method[] methods = targetClass.getMethods();String description = "";for (Method method : methods) {if (method.getName().equals(methodName)) {Class[] clazzs = method.getParameterTypes();if (clazzs.length == arguments.length) {SystemServiceType serviceType = method.getAnnotation(SystemServiceType.class);//得到对应的方法结果Class clazz = serviceType.classType();int type = serviceType.type();description = serviceType.description();log.info("type:" + type);break;}}}return description;}/**** 获取aop拦截到的方法注解的Class* @param pjp* @return*/public static Class getClassByAnno(ProceedingJoinPoint pjp){Class<?> aClass = pjp.getTarget().getClass();Method[] methods = aClass.getMethods();for (Method method : methods) {Annotation[] annotations = method.getAnnotations();for (Annotation annotation : annotations) {// 获取注解的具体类型Class<? extends Annotation> annotationType = annotation.annotationType();//比较当前方法注解是否是SystemServiceType注解if (SystemServiceType.class == annotationType) {log.info("方法:" + method.getName() + "()\t" + SystemServiceType.class.getName());SystemServiceType serviceType = method.getAnnotation(SystemServiceType.class);//得到对应的方法结果Class clazz = serviceType.classType();int type = serviceType.type();String desc = serviceType.description();return clazz;}}}return null;}}
 

 

 

service或controller层调用


 

@SystemServiceType(type = 1,description = "根据pcode获取下级列表",classType = SysDictionaryInfoVO.class)public Object getChildDicVosByPcode(String pcode) throws Exception{List<SysDictionaryInfo> dictionaryInfos = dictionaryInfoMapper.selectChildDictionaryByPcode(pcode);List<SysDictionaryInfoVO> sysDictionaryInfoVOs = new ArrayList<SysDictionaryInfoVO>();return dictionaryInfos;}

这里将会对返回结果dictionaryInfos为SysDictionaryInfo集合,在Around环绕通知进行结果的转换,返回的结果为SysDictionaryInfoVO,

 

由于转换前和转换后的类型不一样,所有需要定义方法的返回类型为Object

 

此外,可以在前置通知、异常通知等通知中进行日志的处理

 

 

参考:http://blog.csdn.net/czmchen/article/details/42392985

           http://blog.csdn.net/liuchuanhong1/article/details/55099753

 

这篇关于springAOP进行自定义注解,用于方法的处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1019648

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法

《JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法》:本文主要介绍JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法,每种方法结合实例代码给大家介绍的非常... 目录引言:为什么"相等"判断如此重要?方法1:使用some()+includes()(适合小数组)方法2

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3