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

目录
  • Spring AOP后置通知修改响应httpstatus
    • 1.定义Aspect
    • 2.使用
    • 3.ApiResponse响应体
    • 4.ApiUtil
  • Spring AOP前后置通知最简单案例
    • 1.首先导jar包
    • 2.写applicationContext.xml
    • 3.项目架构
    • 4.Demo类
    • 5.前后置通知

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为切点,添加了前后置通知,这三个形成了一个横向的切面过程。

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

(0)

相关推荐

  • Spring注解配置AOP导致通知执行顺序紊乱解决方案

    今天在测试Spring的AOP时,发现使用注解配置AOP的方式会导致通知的执行顺序紊乱.[最终通知居然在异常通知之前执行了] 测试代码 (1)定义TargetInterface目标接口 public interface TargetInterface { public abstract void targetProxy(); } (2)定义TargetImpl目标类 @Component("target") public class TargetImpl implements Targ

  • Spring Cloud Gateway 如何修改HTTP响应信息

    Gateway 修改HTTP响应信息 实践Spring Cloud的过程中,使用Gateway作为路由组件,并且基于Gateway实现权限的验证.拦截.过滤,对于下游微服务的响应结果,我们总会有需要修改以统一数据格式,或者修改过滤用户没有权限看到的数据信息,这时候就需要有一个能够修改响应体的Filter. Spring Cloud Gateway 版本为2.1.0 在当前版本,ModifyRequestBodyGatewayFilterFactory是官方提供的修改响应体的参考类,This fi

  • spring boot 使用Aop通知打印控制器请求报文和返回报文问题

    一.简介 开发过程中我们往往需要写许多例如: @GetMapping("/id/get") public Result getById( String id) throws Exception{ log.info("请求参数为:"+id); verify(new VerifyParam("部门id", id)); Result result = new Result("通过id获取部门信息成功!", service.query

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

    目录 Spring AOP后置通知修改响应httpstatus 1.定义Aspect 2.使用 3.ApiResponse响应体 4.ApiUtil Spring AOP前后置通知最简单案例 1.首先导jar包 2.写applicationContext.xml 3.项目架构 4.Demo类 5.前后置通知 Spring AOP后置通知修改响应httpstatus 1.定义Aspect /** * 响应体切面 * 后置通知修改httpstatus * * @author : CatalpaFla

  • Spring AOP 后置处理器使用方式

    目录 1 前言 2 BeanPostProcesser 后置处理器 3 总结 1 前言 在 Spring 的体系中,在前文中已经讲述了IOC 容器以及 Bean的理解,在本文基于之前文章内容将继续 AOP 的源码分享. AOP 是一个很繁杂的知识点,这里先从后置处理器开始. 2 BeanPostProcesser 后置处理器 BeanPostProcesser 在 Spring 是一个很重要的概念,这是容器提供的一个可扩展接口,关于后置处理器 Spring 给出的注释是这样的: 简单来说就是:

  • 一文搞懂Spring AOP的五大通知类型

    目录 一.通知类型 二.环境准备 添加AOP依赖 创建目标接口和实现类 创建通知类 创建Spring核心配置类 编写运行程序 三.添加通知 普通通知 环绕通知(重点) 一.通知类型 Advice 直译为通知,也有人翻译为 “增强处理”,共有 5 种类型,如下表所示. 通知类型 注解 说明 before(前置通知) @Before 通知方法在目标方法调用之前执行 after(后置通知) @After 通知方法在目标方法返回或异常后调用 after-returning(返回通知) @AfterRet

  • Spring之@Aspect中通知的5种方式详解

    目录 @Before:前置通知 案例 对应的通知类 通知中获取被调方法信息 JoinPoint:连接点信息 ProceedingJoinPoint:环绕通知连接点信息 Signature:连接点签名信息 @Around:环绕通知 介绍 特点 案例 对应的通知类 @After:后置通知 介绍 特点 对应的通知类 @AfterReturning:返回通知 用法 特点 案例 对应的通知类 @AfterThrowing:异常通知 用法 特点 案例 对应的通知类 几种通知对比 @Aspect中有5种通知

  • Spring BeanPostProcessor(后置处理器)的用法

    目录 BeanPostProcessor 一.自定义后置处理器演示 二.多个后置处理器 三.显示指定顺序 对BeanPostProcessor接口的理解 为了弄清楚Spring框架,我们需要分别弄清楚相关核心接口的作用,本文来介绍下BeanPostProcessor接口 BeanPostProcessor 该接口我们也叫后置处理器,作用是在Bean对象在实例化和依赖注入完毕后,在显示调用初始化方法的前后添加我们自己的逻辑.注意是Bean实例化完毕后及依赖注入完成后触发的.接口的源码如下 publ

  • 使用spring aop统一处理异常和打印日志方式

    我们很容易写出的代码 我们很容易写出带有很多try catch 和 logger.warn(),logger.error()的代码,这样一个方法本来的业务逻辑只有5行,有了这些,代码就变成了10行或者更多行,如: public ResultDTO<UserDTO> queryUserByCardId(String cardId) { ResultDTO<UserDTO> result = new ResultDTO<UserDTO>(); StringBuilder l

  • Spring AOP的五种通知方式代码实例

    这篇文章主要介绍了Spring AOP的五种通知方式代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 AOP的五种通知方式: 前置通知:在我们执行目标方法之前运行(@Before) 后置通知:在我们目标方法运行结束之后,不管有没有异常(@After) 返回通知:在我们的目标方法正常返回值后运行(@AfterReturning) 异常通知:在我们的目标方法出现异常后运行(@AfterThrowing) 环绕通知:目标方法的调用由环绕通知决定

  • 如何使用Spring AOP的通知类型及创建通知

    写在最前端 1.SpringAOP中共有六种通知类型,只要我们自定义一个类实现对应的接口,它们全都是org.springframework.aop包中的. 2.AOP的连接点可以是方法调用.方法调用本身.类初始化.对象实例化时,但是SpringAOP中全是方法调用,更简单,也最实用 通知名称 接口 前置通知 org.springframework.aop.MethodBeforeAdvice 后置返回通知 org.springframework.aop.AfterReturningAdvice

  • Spring框架基于注解的AOP之各种通知的使用与环绕通知实现详解

    目录 一.基于注解的AOP之各种通知的使用 二.基于注解的AOP之环绕通知 一.基于注解的AOP之各种通知的使用 1.在切面中,需要通过指定的注解将方法标识为通知方法 @Before:前置通知,在目标对象方法执行之前执行 @After:后置通知,在目标对象方法的finally子句中执行 @AfterReturning:返回通知,在目标对象方法返回值之后执行 @AfterThrowing:异常通知,在目标对象方法的catch子句中执行 声明重用写入点表达式 @Pointcut("execution

  • Java 图解Spring启动时的后置处理器工作流程是怎样的

    探究Spring的后置处理器 本次我们主要探究invokeBeanFactoryPostProcessors():后面的代码下次再做解析: 入口代码refresh() AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); // ...... applicationContext.refresh(); public void refresh() throws

随机推荐