English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
After throwingはSpring AOPのアドバイスのタイプです。メソッドが例外を投げた場合、アドバイスが実行されることを保証します。私たちは以下を使用します @AfterThrowing アノテーションを使用してthrowingアドバイスを実現します。
文法:
@AfterThrowing(PointCut="execution(expression) ", throwing="name")
その中で:
PointCut: 関数を選択してください。
execution(expression):
throwing: 返すべき例外の名前。
アプリケーションでafterを実現しましょう-throwingアドバイス。
このセクションでは、前の例を使用します。プロジェクトをダウンロードしたり、前の例でいくつかの修正を行うことができます。
ステップ1: Spring Initializrを開きます http://start.spring.io 。
第2手順: 提供 グループ名前。私たちはグループ名を提供しています com.w3codebox。
ステップ3: 提供しています Artifact Id。Artifact Idを提供 aop-after-throwing-advice-example.。
ステップ4: 追加 Spring Web 依存関係。
ステップ5: クリック 生成ボタンをクリックすると、すべての規格をパッケージ化します。 jar ファイルから、それをローカルシステムにダウンロードします。
ステップ6: 抽出
第7手順: インポートフォルダー、以下の手順を実行してください:
ファイル-> インポート- > 現有のMavenプロジェクト-> 次へ-> フォルダーをブラウズ aop-throwing-advice-example -> 完了。
ステップ8: オープン pom.xml ファイルに、以下を追加します。 AOP 依存関係。それは使用 Spring AOP および AspectJ アスペクト指向プログラミングの入門を行います。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> </dependencies>
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.w3codebox</groupId> <artifactId>aop-after-throwing-advice-example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>aop-after-throwing-advice-example</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </プラグイン </> </ビルド </>
ステップ9: プロジェクト src/main/java フォルダー に com.w3codebox.model のパッケージを
ステップ10: のパッケージ com.w3codebox.modelに Account のクラス。
「アカウント」クラスで以下の操作を行います:
String型の二つの変数を定義しました。 accountNumber および accountType 。 ファイルを右クリック ->ソース->使用フィールドでコンストラクタを生成 Gettersを生成。
ファイルを右クリック->ソース-> Generate Getters and Setters->選択Getters-> Generate 生成 toString()
ファイルを右クリック->ソース->生成toString()
Account.java
package com.w3codebox.model; public class Account { private String accountNumber; private String accountType; public Account(String accountNumber, String accountType) { super(); this.accountNumber = accountNumber; this.accountType = accountType; } public String getAccountType() { return accountType; } public String getAccountNumber() { return accountNumber; } @Override public String toString() { return "Account [accountNumber=" + accountNumber+ ", accountType=" + accountType + "]"; } }
ステップ11: 別の名前 com.w3codebox.service.implのパッケージを
ステップ12: このパッケージで、 AccountServiceImpleのクラス。
このクラスでは、アカウントサービスを定義しています。
AccountServiceImpl.Java
package com.w3codebox.service.impl; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.springframework.stereotype.Service; import com.w3codebox.model.Account; @Service public class AccountServiceImpl implements AccountService { //HashMapにアカウント詳細を保存する private static Map<String, Account> map = null; static { map = new HashMap<>(); //マップにアカウント詳細を追加する map.put("M4546779, new Account("10441117000", "Saving Account"); map.put("K2434567, new Account("10863554577, "Current Account"); } @Override public Account getAccountByCustomerId(String customerId) throws Exception { if (customerId == null) { throw new Exception("Invalid! Customer Id"); } Account account = null; Set<Entry<String, Account>> entrySet = map.entrySet(); for (Entry<String, Account> entry : entrySet) { if (entry.getKey().equals(customerId)) { account = entry.getValue(); } } return account; } }
ステップ13: のパッケージ com.w3codebox.service.impl。 において、 AccountService のインターフェースです。
AccountService.java
package com.w3codebox.service.impl; import com.w3codebox.model.Account; //インターフェースを作成中で、顧客IDが見つからない場合に例外をスローする public interface AccountService { public abstract Account getAccountByCustomerId(String customerId) throws Exception; }
ステップ14: において、 com.w3codebox.aspectのパッケージ。
ステップ15: のパッケージ com.w3codebox.aspect において、 AccountAspect のクラス。
このクラスでは、以下のように投げ後のアドバイス注釈を実装しました @AfterThrowing。 また、以下のように投げ後のアドバイスを定義しました afterThrowingAdvice()メソッド。
AccountAspect.java
package com.w3codebox.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Aspect @Component public class AccountAspect { //after throwing adviceを実装しています @AfterThrowing(value="execution("* com.w3codebox.service.impl.AccountServiceImpl.*(..))",throwing="ex") public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) { System.out.println("メソッド内で例外が投げられた後:"+joinPoint.getSignature()); System.out.println("例外は:"+ex.getMessage()); } }
ステップ16: オープン AopAfterThrowingAdviceExampleApplication.java ファイルに注釈を追加します @EnableAspectJAutoProxy。
注釈はAspectJを持つ処理をサポートします @Aspect 注釈のコンポーネントです。@Configuration注釈と一緒に使用されます。
私たちは@EnableAspectJAutoProxyアノテーションを使用しています。 proxyTargetClass 属性。属性 proxyTargetClass = true を使用する許可を許可します CGLIB (コード生成ライブラリ)プロキシ、デフォルトのインターフェースベースのJDKプロキシメソッドではなく。
ConfigurableApplicationContext はインターフェースであり、ApplicationContextのアプリケーションコンテキストクライアントメソッドに加えて、アプリケーションコンテキストの設定に使用するツールも提供します。
AopAfterThrowingAdviceExampleApplication.java
package com.w3codebox; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.EnableAspectJAutoProxy; import com.w3codebox.model.Account; import com.w3codebox.service.impl.AccountService; import com.w3codebox.service.impl.AccountServiceImpl; @SpringBootApplication //@EnableAspectJAutoProxyアノテーションは、@Aspectアノテーションでマークされたコンポーネントの処理をサポートします。これはXML設定でのタグに似ています。 @EnableAspectJAutoProxy(proxyTargetClass=true) public class AopAfterThrowingAdviceExampleApplication { public static void main(String[] args) { ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args); //アプリケーションコンテキストからaccountオブジェクトを取得 AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class); Account account; try { //例外を生成 account = accountService.getAccountByCustomerId(null); if(account != null) System.out.println(account.getAccountNumber()+"\t"+account.getAccountType()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
すべてのクラスとパッケージを作成した後、プロジェクトディレクトリは以下のようになります:
ステップ17: オープン AopAfterThrowingAdviceExampleApplication.java ファイルをJavaアプリケーションとして実行します。以下のように出力が表示されます: