AOP面向切面编程

AOP:Aspect Oriented Programming(面向切面编程)。通过不修改源代码的方式,在主干里面添加新功能。
AOP底层用的是动态代理:
(1)有接口,使用JDK动态代理
需要创建接口实现类代理对象
(2)没有接口,使用CGLIB动态代理
创建当前类的子类的代理对象
AOP中专业的术语:
1. 连接点
类里面的哪些方法可以被增强,这些方法称为连接点。
2. 切入点
实际真正被增强的方法,称为切入点。
3. 通知(增强)
实际增强的逻辑部分,称为通知。

  • 前置通知
  • 后置通知
  • 环绕通知
  • 异常通知
  • 返回通知

执行顺序为:环绕通知(前),前置通知,切入点方法,返回通知,后置通知,环绕通知(后)
如果有异常:环绕通知(前),前置通知,切入点方法(发生异常前半部分),异常通知,后置通知
4. 切面
把通知应用到切入点的过程,称为切面

AOP操作

spring框架中一般都是基于AspectJ实现AOP操作。
AspectJ不是Spring组成部分,是独立AOP框架,一般把AspectJ和spring框架一起使用,进行AOP操作。
基于AspectJ实现AOP操作

  1. 基于xml配置文件实现
  2. 基于注解方式实现

切入点表达式

(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构:

  • execution([权限修饰符][返回类型][类全路径]方法名称)
    例如想对com.kun.Spring5.BookDao类里面的add方法进行增强
  • execution(* com.kun.Spring5.BookDao.add(…))
    *表示所有的修饰符(public,private等),返回值类型可以步行,…表示参数
  • execution(* com.kun.Spring5.BookDao.*(…))
    对类中所有方法进行增强
  • execution(* com.kun.Spring5..(…))
    对Spring5包下所有类中的所有方法进行增强
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的AOP面向切面编程的测试代码示例,使用Spring框架实现: 首先,创建一个切面类 `LoggingAspect`,用于定义切面逻辑: ```java import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature().getName()); } @After("execution(* com.example.service.*.*(..))") public void afterAdvice(JoinPoint joinPoint) { System.out.println("After method: " + joinPoint.getSignature().getName()); } } ``` 然后,创建一个测试服务类 `UserService`,用于演示AOP的应用: ```java import org.springframework.stereotype.Service; @Service public class UserService { public void createUser(String username) { System.out.println("Creating user: " + username); } public void deleteUser(String username) { System.out.println("Deleting user: " + username); } } ``` 最后,创建一个Spring Boot应用程序,并在启动类进行配置: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.EnableAspectJAutoProxy; @SpringBootApplication @EnableAspectJAutoProxy public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); UserService userService = context.getBean(UserService.class); userService.createUser("John"); userService.deleteUser("John"); } } ``` 在上述示例,`LoggingAspect` 切面类使用 `@Before` 和 `@After` 注解分别定义了在目标方法执行前和执行后的逻辑。切面逻辑会应用于 `UserService` 类的所有方法。 当运行应用程序时,可以看到切面逻辑在方法执行前和执行后打印了相应的日志消息。 这是一个简单的AOP面向切面编程的示例,你可以根据实际需求进行更复杂的切面逻辑定义和应用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值