引入maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.19</version>
</dependency>
创建通知类代码
package org.example.Advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAdvice4 {
//配置统一切点表达式
@Pointcut("execution(void org.example.service.Impl.*.*(..))")
public void myPointcut() {}
@Before("MyAdvice4.myPointcut()")
public void beforeAdvice() {
System.out.println("前置增强");
}
@AfterReturning("MyAdvice4.myPointcut()")
public void afterAdvice() {
System.out.println("后置增强");
}
@Around("MyAdvice4.myPointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
Object proceed = null;
try {
System.out.println("环绕通知的前置通知。。。");
proceed = joinPoint.proceed();
System.out.println("环绕通知的后置通知。。。");
} catch (Throwable e) {
System.out.println("异常通知。。。");
;
} finally {
System.out.println("最终通知。。。");
}
return proceed;
}
@AfterThrowing(pointcut = "MyAdvice4.myPointcut()", throwing = "e")
public void afterThrowingAdvice(Throwable e) {
System.out.println("异常信息为:" + e);
}
}
3、创建增强类接口代码
package org.example.service;
public interface UserService {
void show();
}
4、创建增强类实现类代码
package org.example.service.Impl;
import org.example.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public void show() {
System.out.println("我是增强类代码");
}
}
5、创建配置类
package org.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration //替代配置文件
@ComponentScan(basePackages = "org.example") //替代包扫描
@EnableAspectJAutoProxy //使能够开启代理
public class SpringConfig {
}
6、编写测试类
import org.example.config.SpringConfig;
import org.example.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ApplicationContextTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = applicationContext.getBean(UserService.class);
userService.show();
}
}
7、测试结果
![](https://img-blog.csdnimg.cn/img_convert/e309e1cc83c0f401ff139d1a359ad9df.png)