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

相关文章

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

Python使用自带的base64库进行base64编码和解码

《Python使用自带的base64库进行base64编码和解码》在Python中,处理数据的编码和解码是数据传输和存储中非常普遍的需求,其中,Base64是一种常用的编码方案,本文我将详细介绍如何使... 目录引言使用python的base64库进行编码和解码编码函数解码函数Base64编码的应用场景注意