Spring-AOPの概念と使用法のチュートリアル

春-AOP

1.AOPの基本概念

(1)アスペクト指向プログラミング(アスペクト)、AOPを使用すると、ビジネスロジックの各部分を分離できるため、ビジネスロジックのさまざまな部分間の結合が減り、プログラムの再利用性が向上し、開発。

(2)一般的な説明:ソースコードを変更せず、メイン関数に新しい関数を追加します

(3)ログイン例を使用してAOPを説明する

ここに画像の説明を挿入

2. AOP(基本原則)

a)AOPは最下層で動的プロキシを使用します。動的プロキシには2つの状況があります。

最初 インターフェイスがある場合は、JDK動的プロキシを使用します;クラスのメソッド拡張するために、インターフェイス実装クラスのプロキシオブジェクトを作成します
ここに画像の説明を挿入

インターフェイスのない2番目のケースでは、 CGLIB動的プロキシ;サブクラスのプロキシオブジェクト作成、クラスのメソッドを拡張します
ここに画像の説明を挿入

3. AOP(JDK動的プロキシ)

1)JDK動的プロキシを使用し、Proxyクラスのメソッドを使用してプロキシオブジェクトを作成します

newProxyInstanceメソッドを呼び出します。このメソッドには次の3つのパラメーターがあります。

public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)

最初のパラメーター、クラスローダー

2番目のパラメーターである拡張メソッドが配置されているクラス、このクラスが実装するインターフェースは、複数のインターフェースをサポートします

3番目のパラメーターは、このインターフェースInvocationHandlerを実装し、プロキシオブジェクトを作成し、拡張部分を記述します

2)JDK動的プロキシコードを記述します

//(1)创建接口,定义方法
public interface UserDao {
    
    
 public int add(int a,int b);
 public String update(String id);
}
//(2)创建接口实现类,实现方法
public class UserDaoImpl implements UserDao {
    
    
 @Override
 public int add(int a, int b) {
    
    
 return a+b;
 }
 @Override
 public String update(String id) {
    
    
 return id;
 }
}
//(3)使用 Proxy 类创建接口代理对象
public class JDKProxy {
    
    
 public static void main(String[] args) {
    
    
 //创建接口实现类代理对象
 Class[] interfaces = {
    
    UserDao.class};
 UserDaoImpl userDao = new UserDaoImpl(); 
/** 第一参数,类加载器 
	第二参数,增强方法所在的类,这个类实现的接口,(支持多个接口)
	第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分  */
 UserDao dao =(UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces,
					new UserDaoProxy(userDao));
 int result = dao.add(1, 2);
 System.out.println("result:"+result);
 }
}

//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    
    
 //1 把创建的是谁的代理对象,把谁传递过来
 //有参数构造传递
 private Object obj;
 public UserDaoProxy(Object obj) {
    
    
 this.obj = obj;
 }
 //增强的逻辑
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
 //方法之前
 System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
 //被增强的方法执行
 Object res = method.invoke(obj, args);
 //方法之后
 System.out.println("方法之后执行...."+obj);
 return res;
 }
}

4. AOP(期間)

a)接続ポイント:クラス内のどのメソッドを拡張できるか、これらのメソッドは接続ポイントと呼ばれます

b)エントリポイント:実際に拡張されたメソッドはエントリポイントと呼ばれます

c)通知(拡張):実際の拡張の論理的な部分は通知と呼ばれ、次の5つのタイプに分けられます。

1)事前通知2)事後通知3)周辺通知4)例外通知5)最終通知

d)側面:エントリポイントに通知を適用するプロセス

5.AOP操作

a)Springフレームワークは通常AspectJに基づいてAOP操作を実装します。AspectJはSpringの一部ではありません。独立したAOPフレームワークです。通常、AspectJフレームワークとSpirngフレームワークを一緒に使用してAOP操作を実行します。

b)AspectJに基づくAOP操作の実装:1)xml構成ファイルに基づく実装(2)アノテーションメソッドに基づく実装(使用)

c)関連するjarパッケージを導入する

d)エントリポイントの式は次のとおりです。

1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强 
(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )3)例子如下:
    例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强
		execution(* com.atguigu.dao.BookDao.add(..))2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强
		execution(* com.atguigu.dao.BookDao.* (..))3:对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强
		execution(* com.atguigu.dao.*.* (..))

6. AOP操作(AspectJアノテーション)

//1、创建类,在类里面定义方法
public class User {
    
    
 public void add() {
    
    
 System.out.println("add.......");
 }
}
//2、创建增强类(编写增强逻辑)
//(1)在增强类里面,创建方法,让不同方法代表不同通知类型
//增强的类
public class UserProxy {
    
    
 public void before() {
    
    //前置通知
 System.out.println("before......");
 }
}

<!--3、进行通知的配置-->
<?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>

    <!-- 开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
//增强的类
@Component
@Aspect  //生成代理对象
public class UserProxy {
    
    }

//被增强的类
@Component
public class User {
    
    }

//4、配置不同类型的通知
@Component
@Aspect  //生成代理对象
public class UserProxy {
    
    
      //相同切入点抽取
    @Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void pointdemo() {
    
    

    }

    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "pointdemo()")//相同切入点抽取使用!
    public void before() {
    
    
        System.out.println("before.........");
    }

    //后置通知(返回通知)
    @AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterReturning() {
    
    
        System.out.println("afterReturning.........");
    }

    //最终通知
    @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void after() {
    
    
        System.out.println("after.........");
    }

    //异常通知
    @AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterThrowing() {
    
    
        System.out.println("afterThrowing.........");
    }

    //环绕通知
    @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    
    
        System.out.println("环绕之前.........");

        //被增强的方法执行
        proceedingJoinPoint.proceed();

        System.out.println("环绕之后.........");
    }
}

7.同じメソッドを拡張するために複数の拡張クラスがあり、拡張クラスの優先度を設定します

//(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高
@Component
@Aspect
@Order(1)
public class PersonProxy{
    
     }

8. AOP操作(AspectJ構成ファイル)

<!--1、创建两个类,增强类和被增强类,创建方法(同上一样)-->
<!--2、在 spring 配置文件中创建两个类对象-->
<!--创建对象-->
<bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>
<!--3、在 spring 配置文件中配置切入点-->
<!--配置 aop 增强-->
<aop:config>
 <!--切入点-->
 <aop:pointcut id="p" expression="execution(* com.atguigu.spring5.aopxml.Book.buy(..))"/>
 <!--配置切面-->
 <aop:aspect ref="bookProxy">
 <!--增强作用在具体的方法上-->
 <aop:before method="before" pointcut-ref="p"/>
 </aop:aspect>
</aop:config>

おすすめ

転載: blog.csdn.net/weixin_45496190/article/details/107082732