目次
1。XML構成に基づくスプリングAOP
2。注釈を使用してAOPを構成します
3。aspetjポイントカット関数
4。aspectj通知ノート
5。SpringIOCおよびAOPを実装するゼロ構成
AOP(アスペクト指向プログラミング)は、ランタイム中の事前コンパイル方法と動的エージェントを通じてプログラム機能の水平マルチモジュール統合制御を実装するテクノロジーです。 AOPはOOPのサプリメントであり、Springフレームワークの重要な部分です。ビジネスロジックのさまざまな部分をAOPを使用して分離することができ、それにより、ビジネスロジックのさまざまな部分間の結合を減らし、プログラムの再利用性を改善し、開発の効率を改善することができます。 AOPは、静的織りと動的織りに分けることを意味します。動的織りでは、ターゲットモジュールを変更する必要はありません。スプリングフレームワークはAOPを実装し、注釈を使用してAOPを構成することは、XML構成を使用するよりも便利で直感的です。
1。XML構成に基づくスプリングAOP
AOP関数を実装するための注釈を説明する前に、最初に以前の学習を使用して、XMLを使用してSpring AOP関数を構成して、比較とより良い理解のためです。
1.1新しいMavenプロジェクトを作成し、POM.XMLファイルを追加します。
<Project XMLNS = "http://maven.apache.org/pom/4.0.0" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation = "http://maven.apmen.apmen.apcach.-prigh.-prigh。 apache.org/xsd/maven-4.0.0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> com.zhangguo </groupid> <artifactid> spring </artifactid> <バージョン> 0.0.1-snapshot </version> <packaging> jar </packaging> <name> spring052 </name> <url> http://maven.apache.org </url> <Properties> <Project.build.sourceencoding> utf-8 < > </Properties> <Dependencies> <Dependency> <GroupId> junit </groupId> <artifactid> junit </artifactid> <scope> test </scope> <バージョン> 4.10 </version> </dependency> <依存関係> <groupid> org.springframework </groupid> <artifactid> spring-context </artifactid> <bersion> $ {spring.version} </dependency> <sheplency> <shepency> <groupid>依存関係> <依存関係> <GroupId> cglib </groupId> <Artifactid> cglib </artifactid> <バージョン> 3.2.4 </version> </dependency> </dependencies> </project>1.2プロキシの数学クラスを作成すると、コードは次のとおりです。
パッケージcom.zhangguo.spring052.aop01;/*** Public Class Math {// public int add(int n1、int n2){int result = n1+n2 system.out.println( "+n2+"+result)結果= n2。1.3通知クラスのアドバイスを編集します。AOPで使用する必要があるJavaコードは次のとおりです。
package com.zhangguo.Spring052.aop01;import org.aspectj.lang.JoinPoint;/** * Notification class, cross-cut logic* */public class Advices { public void before(JoinPoint jp){ System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------1.4コンテナの初期化に必要なXMLファイルを構成します。
<?xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/xmlschema springframework.org/schema/p "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/aop spring-aop-4.3.xsd "> <! - proxy object-> <bean id =" math "> </bean> <! - notification-> <bean id =" advices "> </bean> <! - aop構成 - > <aop:config proxy-target-class =" true "> < express = "execution(* com.zhangguo.spring052.aop01.math </豆>
1.5テストコードテスト。
com.zhangguo.spring052.aop01; Import org.springframework.context.applicationcontext; import org.springframework.conpport.classpathxmlapplicationcontext; xml "); Math Math = ctx.getBean(" Math "、Math.class); int n1 = 100、n2 = 5; Math.Add(N1、N1、N2);
実行結果:
2。注釈を使用してAOPを構成します
2.1前の例では、IOCスキャンを実装するためにプロキシクラスの数学を変更します。前の例でXML構成ファイルにBeanを追加することと同等です<! - プロキシオブジェクト - > <bean id = "math"> </bean>、およびMathクラスのコードは次のとおりです。
パッケージcom.zhangguo.spring052.aop02; import org.springframework.stereotyce.service; } // public int sub(int n1、int n2){int result = n1-n2; System.Out.Println( "+n2+"+ println(n1+"+n2+"+result);2.2コードには3つのアノテーションがあります。
com.zhangguo.spring052.aop02; Import org.aspectj.lang.joinpoint; Import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation; */@component@saspepublic classアドバイス{@before( "execution( * com.zhangguo.Spring052.aop02.Math.*(..))") public void before(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------上記のコードは基本的に次の構成と同じです
<! - 通知 - > <bean id = "advices"> </bean> <! - > <aop:config proxy-target-class = "true"> <! - section-> <aps ref = "advices"> <! - slice point-> <aop:aop:aop:pointcut expression = "実行cut1 "/> <! - connect通知メソッドとポイント - > <aop:method =" before "pointcut-ref =" pointcut1 "/> <aop:after method =" after " pointcut-ref = "pointcut1"/> </aop:aspect> </aop:config>
2.3 AOP02.xmlを追加し、IOCの構成に基づいてAspectJ-autoxyノードを追加します。
<?xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/xmlschema springframework.org/schema/p "xmlns:aop =" http://www.springframework.org/schema/aop "xmlns:context =" http://www.springframework.org/schema/context " xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/ org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd "> <コンテキスト:Component-Scanベースパッケージ= "com.zhangguo.spring052.aop02"> </context:component-scan> <aop:aspectj-autoproxy proxy-target-class = "true"> </aop:aspectj-autoproxy> </beans>
2.4テストはコードテストです。Javaは次のとおりです。
パッケージcom.zhangguo.spring052.aop02; Import org.springframework.context.applicationcontext; Import org.springframework.conpport.classpathxmlapplicationcontext; xml "); Math Math = ctx.getBean(" Math "、Math.class); int n1 = 100、n2 = 5; Math.Add(N1、N1、N2);
実行結果:
3。aspetjポイントカット関数
ポイントの関数は、前の例では、com.zhangguo.spring02.mathターゲティングが異なる合計のctions。
@AspectJは、AspectJの特別なポイントカット式を使用して、SpringでサポートされているAspectJ式を説明します。
メソッドポイントカット関数:ターゲットクラスメソッド情報を記述することにより、接続ポイントを定義します。
メソッドパラメーターポイントカット関数:ターゲットクラスメソッドのパラメーター情報を記述することにより、接続ポイントを定義します。
ターゲットクラスポイントカット関数:ターゲットクラスタイプ情報を記述することにより、接続ポイントを定義します。
エージェントクラスポイントカット関数:プロキシクラス情報を記述することにより、接続ポイントを定義します。
一般的なアスペクト式式関数:
最も一般的に使用されるポイントカット関数は次のとおりです。実行(<modifier mode>?<return type mode> <method name mode>(<parameter mode>)<例外モード>?)ポイントカット関数、ほとんどのニーズを満たすことができます。
各点接線関数の関数を表示するために、新しいクラスのストルティルが追加されるようになりました。クラスは次のとおりです。
パッケージcom.zhangguo.spring052.aop03; import org.springframework.stereotype.component( "strutil")public class strutil {public void show(){system.out.println( "hello strutil!");テストコードは次のとおりです。
パッケージcom.zhangguo.spring052.aop03; import org.springframework.context.applicationcontext; import org.springframework.contpathxmlapplicationcontext; ml "); imath math = ctx.getBean(" Math "、Math.class); int n1 = 100、n2 = 5; Math.Add(N1、N2);
3.1ポイントカット関数の実行、通知とセクションの定義は次のとおりです。
パッケージcom.zhangguo.spring052.aop03; Import org.aspectj.lang.joinpoint; Import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation; */@component@saspepublic classアドバイス{@before( "execution( * com.zhangguo.spring052.aop03.math。*(..) ")public void before(joinpoint jp){system.out.println(" --------------------------- "); .aop03パッケージは@after( "execution(*com.zhangguo.spring052.aop03。*。*(..)")public void after(joinpoint jp){(..) "){com.zhangguo.spring052.aop03。*(..)にカットされます。 system.out.println( "---------------------------");操作結果は次のとおりです。
実行(<modifier mode>?<return type mode> <メソッド名モード>(<パラメーターモード>)<例外モード>?)
3.2内のポイントカット関数
//within point-cut function//com.zhangguo.Spring052.aop03 package all methods of all classes are cut into @After("within(com.zhangguo.Spring052.aop03.*)") public void after(JoinPoint jp){ System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------3.3このポイントカット関数
//this point-cut function//Implements any connection point of the proxy object of the IMath interface @After("this(com.zhangguo.Spring052.aop03.IMath)") public void after(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------3.4 argsポイントカット関数
//args point-cut function//Requires that the method has two int type references before it will be weaved into the cross-cutting logic @After("args(int,int)") public void after(JoinPoint jp){ System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------パラメータータイプがベースデータ型ではない場合、パッケージ名が必要です。
3.5 @Annotation Point-cut関数
最初にメソッドで注釈を付けることができる注釈をカスタマイズします
パッケージcom.zhangguo.spring052.aop03; import java.lang.annotation.documented; import java.lang.annotation.ElementType; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; java.lang.nantation.metaget( )@retention(retentionPolicy.runtime)@documentedpublic @interface myanno {} //@annotation point-cut function //メソッドはcom.zhangguo.spring052.aop03.myannoを横断切断Logic @after(com.zhangguo.spring052.aop03.myanno) );パッケージcom.zhangguo.spring052.aop03; import org.springframework.stereeotycome.component( "strutil")public class strutil {@myanno public void show(){system.out.println( "hello strutil!}};実行結果:
@を使用した他のポイントカット関数は、注釈用です
4。aspectj通知ノート
AspectJには6つの通知アノテーションがあり、5つが一般的に使用され、使用される紹介は少なくなります。
最初に、次のコードに示すように、点接線多重化を定義する問題を解決します。ポイントタンジェント関数の内容はまったく同じです。
パッケージcom.zhangguo.spring052.aop04; import org.aspectj.lang.joinpoint; Import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation; */@component@saspepublic classアドバイス{@before( "execution( * com.zhangguo.Spring052.aop04.Math.*(..))") public void before(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------最初に接線を定義してから、次のように多重化できます。
パッケージcom.zhangguo.spring052.aop04; import org.aspectj.lang.joinpoint; Import org.aspectj.lang.annotation.aspect.aspectj.lang.Annotation; */@component@sasdpublic classアドバイス{ // @pointcut( "execution(* com.zhangguo.spring052.aop04.math。*(..)")public void pointcut(){} @before( "pointcut()")befuide before(joinpoint jp){system.out.out.print.名前()) system.out.println( "---------------------------");Advices.javaファイルを変更し、次のようにさまざまな通知タイプを追加します。
パッケージcom.zhangguo.spring052.aop04; import org.aspectj.lang.joinpoint; import org.aspectj.lang.proceedjoinpoint; import org.aspectj.lang.annotation; after; import org.aspectj.lang.annotation.afterturning.asptretuning; lang.annotation.around; Import org.aspectj.lang.annotation.around; Import org.aspectj.lang.annotation.aspect; Import org.aspectj.lang.annotation.before; import aspectj.lang.annotation.pointcut; import org.springframework.stereotype.component;/***通知クラス、クロスカットlogic*/@compent@compublic class advices {// cut point @pointcut( "execution(* com.zhangguo.spring052.ap04.math.a*) /pre-notice @before( "pointcut()")public void before(joinpoint jp){ System.out.println(jp.getSignature().getName()); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Throwable{ System.out.println(pjp.getSignature().getName()); System.out.println("-------------------------------------------"); Object result=pjp.proceed(); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ afterReturning(JoinPoint jp,Object result){ System.out.println(jp.getSignature().getName()); System.out.println("Result is: "+result); System.out.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- System.out.println(jp.getSignature().getName()); System.out.println("Exception message: "+exp.getMessage()); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------実行結果:
5。SpringIOCおよびAOPを実装するゼロ構成
元の例に基づいてゼロ構成を実現するために、以下に示すように新しいユーザーのようなクラスを追加します。
パッケージcom.zhangguo.spring052.aop05; public class user {public void show(){system.out.println( "a user object");このクラスは注釈が付けられておらず、コンテナは自動的に管理されません。 XML構成ファイルがないため、構成情報として1つを使用し、ApplicationCFG.javaファイルは次のとおりです。
パッケージcom.zhangguo.spring052.aop05; Import org.springframework.context.annotation.bean; Import org.springframework.context.annotation.comPonentscan; Import org.springframework.context.annotation.configuration; @configuration //現在のクラスをコンテナとして表すために使用される構成クラス<beans/>@componentscan(basepackages = "com.zhangguo.spring052.aop05") //スキャン範囲はXML構成のノードに相当します<コンテキスト:component-scan/>@@enableaspectjautoproxy(proxytargetclass = true)// <aop:aspectj-autopproxy proxy-targetclass = "true"> aspectj-appro構成では、<bean id = getuser/> @bean public user getuser(){return new user()};このクラスは、基本的にXML構成と1対1の関係がありますが、これはXMLを書くよりも便利です。テストコードは次のとおりです。
com.zhangguo.spring052.aop05; Import org.springframework.context.applicationcontext; import org.springframework.context.annotation.anfigapplicationcontext; args){//クラスApplicationContext ctx = newを介してコンテナを初期化AnnotationConfigscontext(ctx.getbean); = ctx.getbean( "getuser"、user.class); Advices.javaは上記と同じで、変更はありません。実行結果は次のとおりです。
上記は、この記事のすべての内容です。みんなの学習に役立つことを願っています。