SW/Spring Boot

Spring Boot : Spring Boot AOP After Throwing Advice 개념, 예제, 설명, 개요

얇은생각 2023. 3. 28. 07:30
반응형

Spring Boot : Spring Boot AOP After Throwing Advice 개념, 예제, 설명, 개요

 

 

 

Spring Boot AOP After Throwing Advice

스프링 AOP에서는 애프터 던지기 유형이 Adivce 유형입니다. 메소드가 예외를 발생시키는 경우 Advice이 실행되도록 합니다. @After Throwing 주석을 사용하여 after throw 조언을 구현합니다.

 

 

구문:

@AfterThrowing(PointCut="execution(expression) ", throwing="name")

 

 

위치:

PointCut: 기능을 선택합니다.

실행(수식): 그것은 Advice이 적용되어야 하는 표현입니다.

throwing : 반환할 예외의 이름입니다. 

 

 

 

Spring Boot After Throwing Advice Example

이 섹션에서는 이전 예를 사용합니다. 프로젝트를 다운로드하거나 이전 예에서 몇 가지 사항을 수정할 수 있습니다.

 

1단계: Spring Initializr http://start.spring.io을 엽니다.

2단계: 그룹 이름을 입력합니다.  

3단계: 아티팩트 ID를 제공합니다.

4단계: 스프링 웹 종속성을 추가합니다.

5단계: Generate 버튼을 클릭합니다. Generate 버튼을 클릭하면 모든 사양을 jar 파일로 감싸고 로컬 시스템에 다운로드합니다.

6단계: 다운로드한 jar 파일의 압축을 풉니다.

7단계: 다음 단계를 사용하여 폴더를 가져옵니다.

파일 -> 가져오기 -> 기존 메이븐 프로젝트 -> 다음 -> 폴더를 찾습니다.

 

8단계: pom.xml 파일을 열고 다음 AOP 종속성을 추가합니다. Spring AOP 및 Aspect J를 통한 Aspect 지향 프로그래밍의 시작점입니다.

<dependency>  
<groupId>org.springframework.boot</groupId>  
<artifactId>spring-boot-starter-aop</artifactId>  
</dependency>  
</dependencies>

 

 

<?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.xxx</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>  
</plugin>  
</plugins>  
</build>  
</project>

 

 

 

9단계: src/main/java 폴더에 com.xxx.model이라는 이름의 패키지를 생성합니다.

10단계: com.xxx.model 패키지에 Account라는 이름의 클래스를 만듭니다.

 

계정 클래스에서 다음을 수행합니다.

두 개의 변수를 정의했습니다. 계정 번호 및 계정문자열 유형입니다.

파일 -> 소스 -> 필드를 사용하여 생성자를 마우스 오른쪽 버튼으로 클릭합니다.

Getter를 생성합니다.

파일 -> 소스 -> 게터 및 설정자 생성 -> 게터 선택 -> 생성을 마우스 오른쪽 버튼으로 클릭합니다.

toString()을 생성합니다.

파일 -> Source -> Generate to String()을 마우스 오른쪽 버튼으로 클릭합니다.

 

package com.xxx.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.xxx.service.impl라는 이름의 다른 패키지를 만듭니다.

12단계: 이 패키지에서 AccountServiceImple이라는 이름의 클래스를 만듭니다.

이 클래스에서는 계정 서비스를 정의했습니다.

package com.xxx.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.xxx.model.Account;

@Service
public class AccountServiceImpl implements AccountService {

    //storing account detail in the HashMap  
    private static Map < String, Account > map = null;
    static {
        map = new HashMap < > ();
        //adding account detail in the map  
        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.xxx.service.impl 패키지에 AccountService라는 이름의 인터페이스를 만듭니다.

package com.xxx.service.impl;

import com.xxx.model.Account;

//creating interface that throws exception if the customer id not found   
public interface AccountService {

    public abstract Account getAccountByCustomerId(String customerId)
    throws Exception;
}

 

 

14단계: com.xxx.aspect라는 이름의 패키지를 만듭니다.

15단계: com.xxxx.aspect 패키지에 AccountAspect라는 이름의 클래스를 만듭니다.

@AfterThrowing이라는 주석을 사용하여 구현했습니다. 또한 다음에 대한 afterThrowingAdvice() 메소드도 정의했습니다.

던지기 속성에서 정의하는 name(ex)은 조언 메서드의 매개 변수 이름과 일치해야 합니다. 그렇지 않으면 Advice가 실행되지 않습니다.

package com.xxx.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 {

    //implementing after throwing advice      
    @AfterThrowing(value = "execution(* com.javatpoint.service.impl.AccountServiceImpl.*(..))", throwing = "ex")
    public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) {
    
        System.out.println("After Throwing exception in method:" + joinPoint.getSignature());
        System.out.println("Exception is:" + ex.getMessage());
    }
}

 

 

16단계: AopAfterAdvisoryExampleApplication.java 파일을 던지고 @EnableAspectJAutoProxy 주석을 추가합니다.

주석을 사용하면 AspectJ의 @Aspect 주석으로 표시된 구성요소를 처리할 수 있습니다. @Configuration 주석과 함께 사용됩니다.

주석 @EnableAspectJAutoProxy의 proxyTargetClass 특성을 사용했습니다. proxyTargetClass=true 특성을 사용하면 기본 인터페이스 기반 JDK 프록시 접근 방식 대신 CGLIB(Code Generation Library) 프록시를 사용할 수 있습니다.

ConfigurableApplicationContext는 ApplicationContext의 Application Context 클라이언트 메서드와 더불어 Application Context를 구성할 수 있는 기능을 제공하는 인터페이스입니다.

package com.xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.xxx.model.Account;
import com.xxx.service.impl.AccountService;
import com.xxx.service.impl.AccountServiceImpl;

@SpringBootApplication
//@EnableAspectJAutoProxy annotation enables support for handling the components marked with @Aspect annotation. It is similar to tag in the xml configuration.  
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopAfterThrowingAdviceExampleApplication {

    public static void main(String[] args) {
    
        ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args);
        
        //Fetching the account object from the application context  
        AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class);
        Account account;
        
        try {
            //generating exception  
            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();
        }
    }
}

 

 

모든 클래스 및 패키지를 생성한 후 프로젝트 디렉터리는 다음과 같습니다.

Spring Boot : Spring Boot AOP After Throwing Advice 개념, 예제, 설명, 개요 2

 

 

17단계: AopAfterThrowingAdviceExampleApplication.java 파일을 Java Application으로 실행합니다. 아래 그림과 같이 출력이 표시됩니다.

Spring Boot : Spring Boot AOP After Throwing Advice 개념, 예제, 설명, 개요 3

 

반응형