使用Spring AOP的步骤如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
@Aspect
注解进行标记,并且包含需要在目标方法执行前、执行后或抛出异常时执行的通知方法。@Aspect @Component public class LoggingAspect { @Before("execution(public * com.example.MyService.*(..))") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature()); } @After("execution(public * com.example.MyService.*(..))") public void afterAdvice(JoinPoint joinPoint) { System.out.println("After method: " + joinPoint.getSignature()); } @AfterThrowing(pointcut = "execution(public * com.example.MyService.*(..))", throwing = "exception") public void afterThrowingAdvice(JoinPoint joinPoint, Exception exception) { System.out.println("Exception thrown by method: " + joinPoint.getSignature()); System.out.println("Exception: " + exception.getMessage()); } }
上述例子中的切面类包含了三个通知方法:beforeAdvice
、afterAdvice
和afterThrowingAdvice
。@Before
注解用于标记在目标方法执行前执行的通知方法,@After
注解用于标记在目标方法执行后执行的通知方法,@AfterThrowing
注解用于标记在目标方法抛出异常时执行的通知方法。
@EnableAspectJAutoProxy
注解,以启用AOP代理。@SpringBootApplication @EnableAspectJAutoProxy public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@Service public class MyService { public void doSomething() { System.out.println("Doing something..."); } public void throwException() throws Exception { throw new Exception("Something went wrong"); } }
@RestController public class MyController { @Autowired private MyService myService; @GetMapping("/test") public void testAOP() { myService.doSomething(); try { myService.throwException(); } catch (Exception e) { e.printStackTrace(); } } }
以上示例中,MyService
类包含了两个方法:doSomething
和throwException
。在MyController
类中,通过调用MyService
的方法来测试AOP的功能。
当执行/test
接口时,AOP将会在doSomething
方法执行前和执行后打印相应的日志信息,并且在throwException
方法抛出异常时打印异常信息。
注意:为了使AOP生效,需要确保目标类(如MyService
)是由Spring容器管理的(例如通过@Service
注解进行标记)。