열심히 끝까지

디바이스 융합 자바(Java) day66(2) - AOP 관련 용어정리 및 예시 본문

디바이스 융합 자바(Java)기반 풀스택 개발자 양성과정(수업내용)

디바이스 융합 자바(Java) day66(2) - AOP 관련 용어정리 및 예시

노유림 2022. 9. 15. 15:41

   AOP 용어정리


     - Advice : 횡단관심
            ex ) LogAdvice : 로그 횡단관심 어디있나?


     - pointcut : 횡단관심을 적용할 핵심 로직
                     aPointcut == 모든 핵심 로직(부를 이름)
                     bPointcut == ? 핵심 로직
                     expression(표현식)에 어떤 핵심 로직인지 알려줘야함
                     execution(메서드 시그니처)
                             [*] [com.kim.biz..*Impl.*] [(..)]
                             1번째 괄호 [타입 상관없이 모든 로직에 대해서] 
                             2번째 괄호 [패키지 이름 Impl로 끝나는 것의 모든 메서드에 대해서]
                             3번째 괄호 [모든 인자를 의미]   
            ex ) aPointcut - 임의로 정해준 이름(회사마다 달라짐)


     - aspect "결합" 그 자체
                   횡단관심 + 포인트컷(핵심로직) 결합된 것
                   결합시기에 따라 before, after, around,...로 나뉨

 

 

 <aop : 실행할 순서 >


  after : 반환값이 중요하지 않을 때 쓰는 것


  after-returning : 반환값으로 뭔가를 해야할 때 사용
            핵심로직의 반환값을 가지고서 무언가를 처리할 때 사용
            bPointcut이랑 잘 어울리는듯 해서 사용
           ex ) <aop:after-returning method="printLogSelect" pointcut-ref="bPointcut"/> 


  after-throwing : exception으로 예외처리를 해야할 때 사용
           ex ) <aop:after-throwing method="printLogSelect" pointcut-ref="bPointcut"/> 


  before : 뭔가를 진행하기 전에 무조건 실행할 때 사용

 


>> 예시

-----------------LogAdvice.java

package com.ryo.biz.common;

public class LogAdvice {
	public void printLog() {
		System.out.println(">>> 공통로직 <<<     핵심로직 수행 전에 호출됨");
	}
}

 

-----------------LogSelectAdvice.java

package com.ryo.biz.common;

public class LogSelectAdvice {
	public void printLogSelect() {
		System.out.println("데이터를 탐색합니다...");
	}
}

 

-----------------AroundAdvice.java

package com.ryo.biz.common;

import org.aspectj.lang.ProceedingJoinPoint;

// around로 사용할 advice는 반드시 pjp를 input으로 가져야한다!!!
public class AroundAdvice {
	public Object printLogAround(ProceedingJoinPoint pjp) throws Throwable {
		// around는 filter랑 비슷
		// 어디론가 보낼 것이다 했던 정보를 낼름 가로채서 encoding 및 여러 처리를 진행 후
		// 요청상태를 그대로 진행
		// 자기 행동을 진행 후, pointcut을 탈취하고 output 그대로 보냄
		System.out.println("[BEFORE]"); // 안써도 되는 것
		Object returnObj=pjp.proceed(); // 수행해야할 포인트컷
		// pjp.proceed()에 의해 비즈니스 메서드가 수행됨
		System.out.println("[AFTER]"); // 안써도 되는 것
		return returnObj;
	}
}

>> around는 독특한 친구
     : 비즈니스 로직을 사이에 두고
       전 후로 영향력을 행사할 수 있는 친구
       ProceedingJoinPoint pjp(전혀 영향을 주지 않음) 에 input인자를 받아서 진행
       before 뜨고 pjp.proceed 진행 후 after 출력[위의 예시 참고]

 

 

-----------------applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

	<context:component-scan base-package="com.ryo.biz" />
	
	<bean id="logAdvice" class="com.ryo.biz.common.LogAdvice" />
	<bean id="logSelectAdvice" class="com.ryo.biz.common.LogSelectAdvice" /> 
	<bean id="aroundAdvice" class="com.ryo.biz.common.AroundAdvice" />
	<aop:config>
		<aop:pointcut expression="execution(* com.ryo.biz..*Impl.*(..))" id="aPointcut"/>
		<aop:pointcut expression="execution(* com.ryo.biz..*Impl.select*(..))" id="bPointcut"/>
		<aop:pointcut expression="execution(* com.ryo.biz..*Impl.*(..))" id="cPointcut"/>
		<aop:aspect ref="logAdvice">
	<!-- 언제 넣어줄 지 지정, 어떤 포인트에서 넣어줄 지 지정 -->
			<aop:before method="printLog" pointcut-ref="aPointcut"/>	
		</aop:aspect>
		<aop:aspect ref="logSelectAdvice">
			<aop:before method="printLogSelect" pointcut-ref="bPointcut"/>
			<!-- <aop:after-returning method="printLogSelect" pointcut-ref="bPointcut"/> -->
		</aop:aspect>
		<aop:aspect ref="aroundAdvice">
			<aop:around method="printLogAround" pointcut-ref="cPointcut"/>
		</aop:aspect>
	</aop:config>
	
	
</beans>

 

 

>>> 추가

- src/main/resource에 xml파일을 만들 때, 일반 xml이 아닌

   "Spring Bean Configuration File"을 만들어야 함

 

>> 우선 거기서 bean 선택하고 finish 필요한 것은 NameSpaces 통해서 추가할 것