Spring AOP 后置通知修改响应httpstatus方式

 更新时间:2021年12月02日 09:38:00   作者:CatalpaFlat  
这篇文章主要介绍了Spring AOP 后置通知修改响应httpstatus方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Spring AOP后置通知修改响应httpstatus

1.定义Aspect

/**
 * 响应体切面
 * 后置通知修改httpstatus
 *
 * @author : CatalpaFlat
 */
@Component
@Aspect
public class ApiResponseAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 切面
     */
    private final String POINT_CUT = "execution(* com.xxx.web.controller..*(..))";
    @Pointcut(POINT_CUT)
    private void pointcut() {
    }
    @AfterReturning(value = POINT_CUT, returning = "apiResponse", argNames = "apiResponse")
    public void doAfterReturningAdvice2(ApiResponse apiResponse) {
        logger.info("apiResponse:" + apiResponse);
        Integer state = apiResponse.getState();
        if (state != null) {
            ServletRequestAttributes res = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            res.getResponse().setStatus(state);
        }
    }
}

2.使用

2.1.请求体

return ApiUtil.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"the request body is empty");

2.2.参数缺失

return ApiUtil.error(HttpStatus.BAD_REQUEST.value(),"Parameter id is empty");

2.3.权限认证

return ApiUtil.error(HttpStatus.UNAUTHORIZED.value(),"Current requests need user validation");

2.4.与资源存在冲突

return ApiUtil.error(HttpStatus.CONFLICT.value(),"Conflict with resources");

2.5.携带error信息

return ApiUtil.error(HttpStatus.BAD_REQUEST.value(),"There are some mistakes",obj);

3.ApiResponse响应体

public class ApiResponse {
    private Integer state;
    private String message;
    private Object result;
    private Object error;
}

4.ApiUtil

public class ApiUtil {
    /**
     * http回调错误
     */
    public static ApiResponse error(Integer code, String msg) {
        ApiResponse result = new ApiResponse();
        result.setState(code);
        result.setMessage(msg);
        return result;
    }
    /**
     * http回调错误
     */
    public static ApiResponse error(Integer code, String msg,Object error) {
        ApiResponse result = new ApiResponse();
        result.setState(code);
        result.setMessage(msg);
        result.setError(error);
        return result;
    }
}

Spring AOP前后置通知最简单案例

仅仅针对于spring

案例分析:

  • 该案例执行Demo类中的三个方法,分别输出Demo1,Demo2,Demo3
  • 我们以Demo2为切点,分别执行前置通知和后置通知

1.首先导jar包

在这里插入图片描述

2.写applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        
        <!-- 将Demo放入bean容器中 -->
        <bean id="demo" class="com.hym.bean.Demo"></bean>
        <!-- 将前置通知和后置通知也放入到bean容器中  id 自己任意取,后续引用就取id   ,class是全类名   -->
        <bean id ="myBefore" class="com.hym.advice.MyBeforeAdvice"></bean>
        <bean id ="myAfter" class="com.hym.advice.MyAfterAdvice"></bean>
        <aop:config>
        	<!-- 围绕的哪一个切点进行前后置通知  execution(* 全类名+方法名 )  这是固定写法    id 自己取名,后续引用就取id-->
        	<aop:pointcut expression="execution(* com.hym.bean.Demo.Demo2())" id="mypoint"/>
        	<!--  通知      根据advice-ref中的值 来区分是前置通知还是后置通知 。  值就是前后置通知的id  pointcut-ref 是切点的id-->
        	<aop:advisor advice-ref="myBefore" pointcut-ref="mypoint"/>
        	<aop:advisor advice-ref="myAfter" pointcut-ref="mypoint"/>
        </aop:config>
        <!-- r如果存在两个参数,name和id 那么用以下的写法 -->
        <!-- <aop:config>
        	<aop:pointcut expression="execution(* com.hym.bean.Demo.Demo2(String,int) and args(name,id)) " id=""/>
        </aop:config> -->    
</beans>

3.项目架构

在这里插入图片描述

4.Demo类

package com.hym.bean;
public class Demo {
	public void Demo1() {
		System.out.println("Demo1");
	}
	public void Demo2() {
		System.out.println("Demo2");
	}
	public void Demo3() {
		System.out.println("Demo3");
	}
}

5.前后置通知

前置通知:

类中方法需要实现MethodBeforeAdvice

package com.hym.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterAdvice implements AfterReturningAdvice{
	@Override
	public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
		System.out.println("执行后置通知");		
	}	
}

后置通知:

类中方法需要实现AfterReturningAdvice

该接口命名规范与前置通知有差异,需注意

package com.hym.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterAdvice implements AfterReturningAdvice{
	@Override
	public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
		System.out.println("执行后置通知");		
	}	
}

最后测试类:

package com.hym.test;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hym.bean.Demo;
public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Demo demo = ac.getBean("demo",Demo.class);
		demo.Demo1();
		demo.Demo2();
		demo.Demo3();		
	}
}

最终执行结果:

在这里插入图片描述

AOP:面向切面编程

在执行Demo时,是纵向执行的,先Demo1,Demo2,Demo3.

但是我们以Demo2为切点,添加了前后置通知,这三个形成了一个横向的切面过程。

在这里插入图片描述

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 详解hibernate4基本实现原理

    详解hibernate4基本实现原理

    本文通过图文并茂的形式给大家介绍的hibernate4基本实现原理,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-09-09
  • Java中String类的一些常见方法总结

    Java中String类的一些常见方法总结

    这篇文章主要给大家介绍了关于Java中String类的一些常见方法,文中包括了Java中String类的基本概念、构造方式、常用方法以及StringBuilder和StringBuffer的使用,涵盖了字符串操作的各个方面,包括查找、转换、比较、替换、拆分、截取等,需要的朋友可以参考下
    2024-11-11
  • Spring整合Quartz开发代码实例

    Spring整合Quartz开发代码实例

    这篇文章主要介绍了Spring整合Quartz开发代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Java 中 getClass() 方法的使用与原理深入分析(对象类型信息)

    Java 中 getClass() 方法的使用与原理深入分析(对象类型信息)

    在 Java 编程中,getClass() 是一个非常重要的方法,它用于获取对象的运行时类信息,无论是调试代码、反射操作,还是类型检查,getClass() 都扮演着关键角色,本文将深入探讨 getClass() 的使用方法、底层原理以及实际应用场景,感兴趣的朋友一起看看吧
    2024-12-12
  • Java多线程基础 线程的等待与唤醒(wait、notify、notifyAll)

    Java多线程基础 线程的等待与唤醒(wait、notify、notifyAll)

    这篇文章主要介绍了Java多线程基础 线程的等待与唤醒,需要的朋友可以参考下
    2017-05-05
  • idea导入module全流程

    idea导入module全流程

    这篇文章主要介绍了idea导入module全流程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Spring Boot集成redis,key自定义生成方式

    Spring Boot集成redis,key自定义生成方式

    这篇文章主要介绍了Spring Boot集成redis,key自定义生成方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • 解决mybatis plus报错Invalid bound statement (not found):问题

    解决mybatis plus报错Invalid bound statement 

    在使用MyBatis时遇到InvalidBoundStatement异常,常因多个MapperScan配置冲突或者包扫描路径设置错误,解决方法包括保留一个MapperScan声明、检查jar包冲突、确保命名空间和扫描路径正确,使用@TableId注解指定主键
    2024-11-11
  • SpringBoot切面拦截@PathVariable参数及抛出异常的全局处理方式

    SpringBoot切面拦截@PathVariable参数及抛出异常的全局处理方式

    这篇文章主要介绍了SpringBoot切面拦截@PathVariable参数及抛出异常的全局处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • SpringAop源码及调用过程概述

    SpringAop源码及调用过程概述

    这篇文章主要介绍了SpringAop源码及调用过程概述,Spring AOP(面向切面编程)是Spring框架的一个重要特性,它提供了一种在程序运行期间动态地将额外的行为织入到代码中的方式,需要的朋友可以参考下
    2023-10-10

最新评论