Springboot如何使用AOP

本文介绍了Springboot中如何引入并使用AOP,包括添加依赖、定义切面类及连接点、切点、切面和通知的概念解释,帮助开发者理解在Springboot中何时何地进行方法增强。
摘要由CSDN通过智能技术生成

切面的包
在这里插入图片描述
1:springboot 不自带Aop 需要自己添加依赖

   <!--begin AOP-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
   <!--end-->

2:直接@Aspect写切面类就行了
1:连接点:可以理解为需要被增强的方法
2:切点:感觉可以理解为 连接点的集合,描述的是 “ 何处 ” 的概念
在这里插入图片描述
3:切面:可以定义切点 通知
4:通知:@Before @After等等 描述的是 ” 何时 “ 的概念

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用SpringBoot AOP的步骤: 1. 首先,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 2. 创建一个切面类,使用@Aspect注解标记该类,并在该类中定义切点和通知。 ```java @Aspect @Component public class MyAspect { @Pointcut("execution(* com.example.demo.service.*.*(..))") public void pointcut() {} @Before("pointcut()") public void before(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature().getName()); } @After("pointcut()") public void after(JoinPoint joinPoint) { System.out.println("After method: " + joinPoint.getSignature().getName()); } } ``` 3. 在应用程序主类上添加@EnableAspectJAutoProxy注解,启用自动代理。 ```java @SpringBootApplication @EnableAspectJAutoProxy public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 4. 在需要使用AOP的类或方法上添加自定义注解,并在切面类中使用@Around注解来拦截该注解。 ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation {} @Around("@annotation(com.example.demo.aspect.MyAnnotation)") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before method: " + joinPoint.getSignature().getName()); Object result = joinPoint.proceed(); System.out.println("After method: " + joinPoint.getSignature().getName()); return result; } @Service public class MyService { @MyAnnotation public void doSomething() { System.out.println("Doing something..."); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值