spring5筆記之AOP(二)
阿新 • • 發佈:2022-03-20
1、建立類,在類裡面定義方法
public class User {
public void add() {
System.out.println("add.......");
}
}
2、建立增強類(編寫增強邏輯)
(1)在增強類裡面,建立方法,讓不同方法代表不同通知型別
//增強的類
public class UserProxy {
public void before() {//前置通知
System.out.println("before......");
}
}
3、進行通知的配置
(1)在 spring 配置檔案中,開啟註解掃描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 開啟註解掃描 -->
<context:component-scan base
package="com.atguigu.spring5.aopanno"></context:component-scan>
(2)使用註解建立 User 和 UserProxy 物件
(3)在增強類上面添加註解 @Aspect
//增強的類@Component
@Aspect //生成代理物件
public class UserProxy {
(4)在 spring 配置檔案中開啟生成代理物件
<!-- 開啟 Aspect 生成代理物件-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4、配置不同型別的通知
(1)在增強類的裡面,在作為通知方法上面新增通知型別註解,使用切入點表示式配置
//增強的類
@Component
@Aspect //生成代理物件
public class UserProxy {
//前置通知
//@Before 註解表示作為前置通知
@Before(value = "execution(* com.study.spring5.aopanno.User.add(..))")
public void before() {
System.out.println("before.........");
}
//後置通知(返回通知)
@AfterReturning(value = "execution(*com.study.spring5.aopanno.User.add(..))")
public void afterReturning() {
System.out.println("afterReturning.........");
}
//最終通知
@After(value = "execution(* com.study.spring5.aopanno.User.add(..))")
public void after() {
System.out.println("after.........");
}
//異常通知
@AfterThrowing(value = "execution(*
com.study.spring5.aopanno.User.add(..))")
public void afterThrowing() {
System.out.println("afterThrowing.........");
}
//環繞通知
@Around(value = "execution(* com.study.spring5.aopanno.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws
Throwable {
System.out.println("環繞之前.........");
//被增強的方法執行
proceedingJoinPoint.proceed();
System.out.println("環繞之後.........");
}
}
5、相同的切入點抽取
//相同切入點抽取
@Pointcut(value = "execution(* com.study.spring5.aopanno.User.add(..))")public void pointdemo() {
}
//前置通知
//@Before 註解表示作為前置通知
@Before(value = "pointdemo()")
public void before() {
System.out.println("before.........");
}
6、有多個增強類多同一個方法進行增強,設定增強類優先順序
(1)在增強類上面添加註解 @Order(數字型別值),數字型別值越小優先順序越高
@Component
@Aspect
@Order(1)
public class PersonProxy
7、完全使用註解開發
(
1)建立配置類,不需要建立 xml 配置檔案
@Configuration
@ComponentScan(basePackages = {"com.atguigu"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}