本文介绍SpringAOP基于注解开发的详细步骤。
1. 定义切面类并标记为@Aspect
- 创建一个切面类,其中包含各种通知(Advice)方法,并使用@Aspect注解标记该类为切面。
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.MyService.*(..))")
public void beforeMethodExecution() {
System.out.println("Before method execution: Logging...");
}
}
2. 定义通知方法并使用相应的注解
- 在切面类中定义通知方法,并使用
@Before、@After、@Around等注解来标记不同类型的通知。
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.MyService.*(..))")
public void beforeMethodExecution() {
System.out.println("Before method execution: Logging...");
}
}
3. 定义切点表达式
- 使用切点表达式(Pointcut Expression)来定义哪些连接点会被切面影响。
@Before("execution(* com.example.MyService.*(..))")
4. 在目标类中添加相关注解
- 在目标类中添加@Component或@Service等注解,确保Spring容器能够扫描到该类。
import org.springframework.stereotype.Service;
@Service
public class MyService {
public void doSomething() {
System.out.println("Doing something...");
}
}
5. 配置Spring容器
- 确保在Spring配置文件中启用注解驱动的AOP功能。
<!-- 启用基于注解的AOP -->
<context:component-scan base-package="com.example" />
<aop:aspectj-autoproxy />
原文链接: https://blog.csdn.net/2401_82884096/article/details/137868622