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

相关文章

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S