【Spring Security】 拦截器案例

Metadata

title: 【Spring Security】 拦截器案例
date: 2023-02-03 10:52
tags:
  - 行动阶段/完成
  - 主题场景/组件
  - 笔记空间/KnowladgeSpace/ProgramSpace/ModuleSpace
  - 细化主题/Module/SpringSecurity
categories:
  - SpringSecurity
keywords:
  - SpringSecurity
description: 【Spring Security】 拦截器案例

【Spring Security】 拦截器案例

undefined

入门案例

  1. 自定义一个注解,我们对标识了这个注解的方法进行拦截
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface TestInterceptor {
    String value();
}
  1. 添加拦截器,实现 MethodInterceptor 接口。
public class MyMethodInterceptor implements MethodInterceptor {


    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        Object result = null;
        try {
            System.out.println("方法执行之前:" + methodInvocation.getMethod().toString());
            String name = methodInvocation.getMethod().getName();
            System.out.println(name + "开始执行");
            result = methodInvocation.proceed();
            System.out.println("方法执行之后:" + methodInvocation.getMethod().toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
    }
}
  1. 配置 Advisor,将切点,拦截器加入到 DefaultPointcutAdvisor 中。
@Configuration
public class AopConfig {

    // 拦截方法的SpEL表达式,这里表示拦截标记了TestInterceptor注解的方法
    public static final String traceExecution = "@annotation(org.pearl.springbootsecurity.demo.aop.TestInterceptor)";

    /**
     * 对切点进行增强
     */
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor() {
        // 创建拦截器
        MyMethodInterceptor interceptor = new MyMethodInterceptor();
        // 配置切点
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(traceExecution);
        // 配置增强类advisor
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(interceptor);
        return advisor;
    }
}
  1. 添加 AOP 包
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  1. 启动项目,测试