一例として、出力ログを使用しました。自動的にログインするためのサービスへのアクセス方法
1.プロジェクトを作成し、春-AOPをインポートし、依存aspectjweare
< 依存> <! - 春IOC:春他の機能は後で使用し、依存IOCに導入しなければならない- > < 依存> < groupIdを> org.springframework </ groupIdを> < たartifactId >春・コンテキスト</ たartifactId > < バージョン> 5.0.2.RELEASE </ バージョン> </ 依存関係> <! - 春春AOP-AOPプログラミングパッケージ自体- > < 依存> < groupIdを> ORG。springframework </groupId > < たartifactId >春AOP </ たartifactId > < バージョン> 5.0.2.RELEASE </ バージョン> </ 依存関係> <! - サードパーティ製のキット(使用可能なポイントカット表現構文)春依存- > < 依存> < groupIdを> org.aspectj </ groupIdを> < たartifactId > aspectjweaver </ たartifactId > < バージョン> 1.8.7 </ バージョン> </依存関係> </ 依存関係>
2.サービスのインタフェースと実装を作成します。
パッケージcom.lemon.service。 パブリック インターフェイスLemonService { ボイド(保存)。 無効)(削除します。 空アップデート(); }
パッケージcom.lemon.service.impl。 輸入com.lemon.service.LemonService。 パブリック クラス LemonServiceImplは実装LemonServiceは{ @Override 公共 ボイドセーブ(){ System.out.printlnは( "新增" ); } @Override 公共 ボイドは、削除(){ System.out.printlnは( "删除" )。 } @Override 公共 ボイド更新(){ System.out.printlnは( "修改" )。 } }
3.クラスのセクションを作成します。
パッケージcom.lemon.log; / ** *ログインアスペクトクラス * / パブリック クラスLogAspect { / ** *通知方法(以前にターゲットに挿入法) * / 公共 ボイドWRITELOG(){ System.out.printlnは(「前======= " ); } }
4.設定アスペクトクラス
<?XMLバージョン= "1.0"エンコード= "UTF-8" ?> < 豆のxmlns = "http://www.springframework.org/schema/beans" のxmlns:XSI = "http://www.w3.org/2001 / XMLスキーマ・インスタンス" のxmlns:AOP = "http://www.springframework.org/schema/aop" のxsi:schemaLocationの=" http://www.springframework.org/schema/beansのhttp://www.springframework。 ORG /スキーマ/豆/春-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd」> <! - 1 。创建目标对象- > < ビーンID = "lemonService" クラス= "com.lemon。 <! - 2.オブジェクトのセクションを作成します- > < 豆上記ID = "logAspect" クラス= "com.lemon.log.LogAspect" /> <! - 3.設定セクション- > < AOP:設定> <! - 切断されたコンフィギュレーション=通知(アドバイス)+ポイントカット(ポイントカット)- > <! - REF:クラスオブジェクト参照部 - > < AOP:アスペクトREF = "logAspect" > <! - 定義されたエントリポイント- > <! - ID:別名ポイントカット定義 の式:ポイントカット式(切断方法のために定義された必要性を) - > < AOP:ポイントカットID = "PT"表現= "実行(* com.lemon.service.impl.LemonServiceImpl *(..))" /> <! - 定義された通知- > <! - 方法:通知方法アスペクトクラスとして使用する方法 pointcut- REF:関連エントリー・ポイント - > <! - 事前通知- > < AOP:前メソッド= "WRITELOG" ポイントカット-REF = "白金" /> </ AOP:アスペクト> </ AOP:設定> </ 豆>
5.テスト
パッケージcom.lemon。 輸入com.lemon.service.LemonService。 輸入org.springframework.context.ApplicationContext; 輸入org.springframework.context.support.ClassPathXmlApplicationContext; // 测试AOP パブリック クラスアプリ{ 公共 静的 ボイドメイン(文字列[]引数){ ApplicationContextのAC = 新しい ClassPathXmlApplicationContext( "クラスパス:春/ ApplicationContextの-aop.xml" )。 LemonService lemonService =(LemonService)ac.getBean( "lemonService" )。 System.out.println( "代理对象" +lemonService.getClass())。 lemonService.save(); lemonService.delete(); lemonService.update(); } }