什么是AOP
AOP(Aspect Oriented Programming),即面向切面编程,是一种程序设计思想,它将一些跟业务无关的功能抽离出来,这些跟业务无关的功能称为切面(Aspect),通过切面将这些功能横切到各个业务模块中,从而达到模块间解耦,同时提高程序的可重用性。
Java实现AOP
Java实现AOP的方式有很多,比如Spring AOP、AspectJ等,本文以Spring AOP为例,介绍如何使用Spring AOP实现AOP面向切面编程。
使用步骤
- 引入Spring AOP的依赖,在Maven中,可以在pom.xml文件中加入以下依赖:
org.springframework.boot spring-boot-starter-aop - 定义切面,切面需要实现org.aspectj.lang.ProceedingJoinPoint接口,并实现其中的proceed()方法,该方法就是用来实现切面的逻辑,例如:
@Aspect public class LogAspect { @Around("execution(* com.example.service.*.*(..))") public Object log(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("start log:" + joinPoint.getSignature().getName()); Object proceed = joinPoint.proceed(); System.out.println("end log:" + joinPoint.getSignature().getName()); return proceed; } }
- 配置Spring AOP,在Spring Boot项目中,只需要在启动类上加上@EnableAspectJAutoProxy注解即可,例如:
@SpringBootApplication @EnableAspectJAutoProxy public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
- 在需要被横切的业务方法上加上@Aspect注解,例如:
@Service public class UserService { @Aspect public void save() { System.out.println("save user"); } }
以上就是使用Spring AOP实现AOP面向切面编程的全部步骤,它可以让我们更方便地将一些跟业务无关的功能抽离出来,从而提高程序的可重用性。