例子是通过springboot项目内的自定义注解的方式,通过自定义注解来使用aop对需要执行的方法做一些操作的,废话不多说直接上代码
1.首先pom.xml文件里添加aop的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.4.4</version>
</dependency>
2.在Application类上开启注解
@SpringBootApplication
@ComponentScan(basePackages = "com")
@Transactional
//开启aspect 默认未false使用jdk的动态代理 true表示使用cglib动态代理
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class BxApplication {
public static void main(String[] args) {
SpringApplication.run(BxApplication.class, args);
}
}
3.编写自定义注解类,如果想在哪个方法上使用aop,直接在方法上声明该注解便可
//METHOD声明在方法上使用
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Doc {
}
4.编写aop类
@Component
@Aspect
public class Aops {
//声明切入点,@Doc自定义注解出现在哪个方法上就对哪个方法生效
@Pointcut("@annotation(com.a1.aop.Doc)")
private void pointcut(){
}
//前置通知,方法执行前通知
@Before("pointcut()")
private void befor(){
System.out.println("befor执行了");
}
//后置通知,方法执行后通知
@After("pointcut()")
private void after(){
System.out.println("after执行了");
}
//环绕通知,在方法执行前有提示,在方法执行后有提示
@Around("pointcut()")
private Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println("around执行了");
Object result = point.proceed();
System.out.println("around结束了");
return result;
}
}
5.编写测试类,本例子是编写了一个Controller层
@Controller
@RequestMapping("/con")
public class TestController {
@RequestMapping("/aop")
//自定义注解
@Doc
public void test(){
System.out.println("我就是要执行的方法");
}
}
6.启动项目:
在浏览器输入http://localhost:8080/con/aop
7.结果是:
8.小例子总结:
可以看出环绕通知是方法执行前和执行后都有通知提示,并且开始前的通知在前置通知之前,结束后的通知在后置通知之后,可以根据实际情况选择需要的通知方法。
有写的不清楚的地方还请大家不吝赐教,共同探讨、共同学习、共同成长!