SW/Spring Boot

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

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

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

 

 

 

Spring Boot  AOP Around Advice

Around Advice은 @Around 주석으로 표시됩니다. 조인 지점 전후에 실행됩니다. 그것은 가장 강력한 Advice입니다. 또한 최종 사용자가 Proceeding JoinPoint를 처리할 수 있는 제어 기능을 제공합니다.

애플리케이션에서 Advice에 대해 구현해 보겠습니다.

 

 

 

스프링 부츠 어라운드 어드바이스 예

1단계: 스프링 Initializr http://start.spring.io을 엽니다.

2단계: 그룹 이름을 입력합니다. 그룹명 com.xxx를 제공하였습니다.

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

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

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

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

 

 

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

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

파일 -> 가져오기 -> 기존 메이븐 프로젝트 -> 다음 -> 폴더 검색 - aop-around-advisory-example -> Finish를 선택합니다.

 

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">  
<modelVersion>4.0.0</modelVersion>  
<parent>  
<groupId>org.springframework.boot</groupId>  
<artifactId>spring-boot-starter-parent</artifactId>  
<version>2.2.2.RELEASE</version>  
<relativePath/> <!-- lookup parent from repository -->  
</parent>  
<groupId>com.xxx</groupId>  
<artifactId>aop-around-advice-example</artifactId>  
<version>0.0.1-SNAPSHOT</version>  
<name>aop-around-advice-example</name>  
<description>Demo project for Spring Boot</description>  
<properties>  
<java.version>1.8</java.version>  
</properties>  
<dependencies>  
<dependency>  
<groupId>org.springframework.boot</groupId>  
<artifactId>spring-boot-starter-web</artifactId>  
</dependency>  
<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>  
<exclusions>  
<exclusion>  
<groupId>org.junit.vintage</groupId>  
<artifactId>junit-vintage-engine</artifactId>  
</exclusion>  
</exclusions>  
</dependency>  
</dependencies>  
<build>  
<plugins>  
<plugin>  
<groupId>org.springframework.boot</groupId>  
<artifactId>spring-boot-maven-plugin</artifactId>  
</plugin>  
</plugins>  
</build>  
</project>

 

 

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

10단계: BankService라는 이름으로 위의 패키지에 클래스를 만듭니다.

이 클래스에서는 displayBalance()라는 메서드를 정의했습니다. 그것은 계좌 번호를 확인합니다. 계정 번호가 일치하면 총 금액이 반환되고 그렇지 않으면 메시지가 반환됩니다.

package com.javatpoint.service;

import org.springframework.stereotype.Service;

@Service
public class BankService {

    public void displayBalance(String accNum) {
        System.out.println("Inside displayBalance() method");
        if (accNum.equals("12345")) {
            System.out.println("Total balance: 10,000");
        } else {
            System.out.println("Sorry! wrong account number.");
        }
    }
}

 

 

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

12단계: BankAspect라는 이름으로 위의 패키지에 클래스를 만듭니다.

다음 클래스에서는 logDisplayingBalance() aroundAdvice() 메서드라는 두 가지 메서드를 정의했습니다.

package com.xxx.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//Enables the spring AOP functionality in an application  
@Aspect
@Component
public class BankAspect {

    //Displays all the available methods i.e. the advice will be called for all the methods  
    @Pointcut(value = "execution(* com.javatpoint.service.BankService.*(..))")
    private void logDisplayingBalance() {}
    
    //Declares the around advice that is applied before and after the method matching with a pointcut expression  
    @Around(value = "logDisplayingBalance()")
    public void aroundAdvice(ProceedingJoinPoint jp) throws Throwable {
    
        System.out.println("The method aroundAdvice() before invokation of the method " + jp.getSignature().getName() + " method");
        try {
            jp.proceed();
        } finally {

        }
        System.out.println("The method aroundAdvice() after invokation of the method " + jp.getSignature().getName() + " method");
    }
}

 

 

13단계: AopAroundAdviceExampleApplication.java 파일을 열고 주석 @EnableAspectJAuto Proxy를 추가합니다.

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

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.service.BankService;

@SpringBootApplication
//@EnableAspectJAutoProxy annotation enables support for handling the components marked with @Aspect annotation. It is similar to tag in the xml configuration.  
@EnableAspectJAutoProxy
public class AopAroundAdviceExampleApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(AopAroundAdviceExampleApplication.class, args);

		// Fetching the employee object from the application context.  
        BankService bank = context.getBean(BankService.class);
        
        // Displaying balance in the account  
        String accnumber = "12345";
        bank.displayBalance(accnumber);
        
        // Closing the context object  
        context.close();
    }
}

 

 

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

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

 

 

이제 응용 프로그램을 실행합니다.

14단계: AopAroundAdviceExampleApplication.java를 열고 Java Application으로 실행합니다.

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

 

 

위의 출력에서, advice() 주변의 메소드가 두 번 호출하는 것을 볼 수 있습니다. 첫째, displayBalance() 메서드를 실행하기 전, 둘째, displayBalance() 메서드를 실행한 후입니다.

반응형