springboot之web工程添加切面

1. springbooot工程中引入AOP依赖

    <dependencies>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

2. 创建切面类

package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {

    // 定义切点
    private final String POINT_CUT = "execution( * com.example.controller.*.*(..))";

    // 用于切入点书写简化
    @Pointcut(value = POINT_CUT)
    public void pt1() {
    }


    @Before("pt1()")
    public void before(JoinPoint joinPoint) {
        System.out.println("前置通知:" + joinPoint.getSignature().getName());
    }

    //可以拿到返回结果,方法正常退出时执行
    @AfterReturning(value = "pt1()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("后置通知:" + result);
    }

    //抛出异常会执行此方法
    @AfterThrowing(value = "pt1()", throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint, Throwable exception) {
        System.out.println("异常通知:" + joinPoint.getSignature().getName());
    }

    // 相当于finally代码块:不管是否抛出异常都会执行
    @After(value = "pt1()")
    public void after(JoinPoint joinPoint) {
        System.out.println("最终通知:" + joinPoint.getSignature().getName());
    }

    @Around(value = "pt1()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        // 获取当前方法对象
        Method method = methodSignature.getMethod();
        Object obj = null;
        try {
            System.out.println("环绕通知之前置处理");
            obj = proceedingJoinPoint.proceed();
            System.out.println("环绕通知之后置处理");
        } catch (Throwable throwable) {

            System.out.println("环绕通知之异常处理");
        }finally {
            System.out.println("环绕通知之最终处理");
        }
        return obj;
    }

}
  • @Component:将切面类交给容器管理
  • @Aspect:标识这是个切面类
  • 这里配置了前置、后置、最终、异常、环绕通知

至此,切面已经成功添加到工程中去了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 中,你可以使用 `AspectJAutoProxyRegistrar` 类来实现在运行时动态注册切面。下面是一种实现方式: 1. 首先,在 Spring Boot 的主配置类上添加 `@EnableAspectJAutoProxy` 注解,启用 AspectJ 自动代理功能。 ```java import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableAspectJAutoProxy public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 2. 创建一个切面类,实现你的业务逻辑。例如,创建一个名为 `CustomAspect` 的类。 ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class CustomAspect { @Before("execution(* com.example.demo.service.YourService.*(..))") public void beforeMethod() { // 在这里编写你的切面逻辑 // 例如,在目标方法执行前执行某些操作 } } ``` 3. 在运行时动态注册切面,可以通过编程的方式将切面添加Spring 的 Bean 容器中。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; @Configuration public class AspectJAutoProxyRegistrar implements ImportAware { private AnnotationAttributes enableAspectJAutoProxy; @Override public void setImportMetadata(AnnotationMetadata importMetadata) { this.enableAspectJAutoProxy = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableAspectJAutoProxy.class.getName(), false)); } @Autowired private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { // 创建切面类的实例 CustomAspect customAspect = new CustomAspect(); // 注册切面类的 BeanDefinition BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory; beanDefinitionRegistry.registerBeanDefinition(CustomAspect.class.getName(), BeanDefinitionBuilder.genericBeanDefinition(CustomAspect.class, () -> customAspect).getBeanDefinition()); // 设置切面类的相关属性 AutowireCapableBeanFactory autowireCapableBeanFactory = beanFactory.getAutowireCapableBeanFactory(); if (autowireCapableBeanFactory instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) autowireCapableBeanFactory) .registerResolvableDependency(CustomAspect.class, customAspect); } } } ``` 请根据你的实际情况修改上述代码,并将 `CustomAspect` 替换为你自己的切面类。这样,在运行时启动 Spring Boot 应用程序时,切面类将被动态注册到 Spring 的 Bean 容器中,并且会自动应用到符合切点表达式的目标方法上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值