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进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

Spring Boot 常用注解整理(最全收藏版)

《SpringBoot常用注解整理(最全收藏版)》本文系统整理了常用的Spring/SpringBoot注解,按照功能分类进行介绍,每个注解都会涵盖其含义、提供来源、应用场景以及代码示例,帮助开发... 目录Spring & Spring Boot 常用注解整理一、Spring Boot 核心注解二、Spr

详解如何在SpringBoot控制器中处理用户数据

《详解如何在SpringBoot控制器中处理用户数据》在SpringBoot应用开发中,控制器(Controller)扮演着至关重要的角色,它负责接收用户请求、处理数据并返回响应,本文将深入浅出地讲解... 目录一、获取请求参数1.1 获取查询参数1.2 获取路径参数二、处理表单提交2.1 处理表单数据三、

Oracle 通过 ROWID 批量更新表的方法

《Oracle通过ROWID批量更新表的方法》在Oracle数据库中,使用ROWID进行批量更新是一种高效的更新方法,因为它直接定位到物理行位置,避免了通过索引查找的开销,下面给大家介绍Orac... 目录oracle 通过 ROWID 批量更新表ROWID 基本概念性能优化建议性能UoTrFPH优化建议注

Pandas进行周期与时间戳转换的方法

《Pandas进行周期与时间戳转换的方法》本教程将深入讲解如何在pandas中使用to_period()和to_timestamp()方法,完成时间戳与周期之间的转换,并结合实际应用场景展示这些方法的... 目录to_period() 时间戳转周期基本操作应用示例to_timestamp() 周期转时间戳基

在 PyQt 加载 UI 三种常见方法

《在PyQt加载UI三种常见方法》在PyQt中,加载UI文件通常指的是使用QtDesigner设计的.ui文件,并将其转换为Python代码,以便在PyQt应用程序中使用,这篇文章给大家介绍在... 目录方法一:使用 uic 模块动态加载 (不推荐用于大型项目)方法二:将 UI 文件编译为 python 模

Python将字库文件打包成可执行文件的常见方法

《Python将字库文件打包成可执行文件的常见方法》在Python打包时,如果你想将字库文件一起打包成一个可执行文件,有几种常见的方法,具体取决于你使用的打包工具,下面就跟随小编一起了解下具体的实现方... 目录使用 PyInstaller基本方法 - 使用 --add-data 参数使用 spec 文件(

Python的pip在命令行无法使用问题的解决方法

《Python的pip在命令行无法使用问题的解决方法》PIP是通用的Python包管理工具,提供了对Python包的查找、下载、安装、卸载、更新等功能,安装诸如Pygame、Pymysql等Pyt... 目录前言一. pip是什么?二. 为什么无法使用?1. 当我们在命令行输入指令并回车时,一般主要是出现以

Java Jackson核心注解使用详解

《JavaJackson核心注解使用详解》:本文主要介绍JavaJackson核心注解的使用,​​Jackson核心注解​​用于控制Java对象与JSON之间的序列化、反序列化行为,简化字段映射... 目录前言一、@jsonProperty-指定JSON字段名二、@JsonIgnore-忽略字段三、@Jso

通过C#获取Excel单元格的数据类型的方法详解

《通过C#获取Excel单元格的数据类型的方法详解》在处理Excel文件时,了解单元格的数据类型有助于我们正确地解析和处理数据,本文将详细介绍如何使用FreeSpire.XLS来获取Excel单元格的... 目录引言环境配置6种常见数据类型C# 读取单元格数据类型引言在处理 Excel 文件时,了解单元格