Spring

[Spring] 뉴렉처 AOP 강의 필기

728x90
반응형

AOP강좌
- 1강 AOP란?
스프링은 아니고 방법론! Aspect Oriented Programming: 관점 지향 프로그래밍.
이전까지는 주 업무 로직에만 초점을 두고 설계했다. 
주 업무 로직 외에 부가적인 로직(보조 업무)들이 있다.

사용자는 주 업무 로직에 집중하지만, 개발자나 관리자의 경우 주 업무 로직 외에 보조적인 업무 로직들 또한 관리해야 한다.
사용자와는 다른 관점에서 프로그램을 나눈 다는 의미에서 AOP라고 한다.
객체지향 프로그래밍보다 좀더 큰 개념이라 할 수 있다. 

주 업무로직은 객체로, 실질적 업무는 매서드로 만들어짐.
필요에 따라 '로그처리, 보안처리, 트랜잭션 처리' 등이 주 업무 로직에 추가 될 필요가 있다.
주 로직의 앞, 뒤에서 처리. 샌드위치(Cross-cutting Concern) 방식

기존에는 주 업무로직에 코드를 기입하고 주석처리 등의 수정을 통해 사용했다. (직접 코드를 손대야 하는 위험이 존재)
외부에서 보조로직을 뺐다 꽂았다를 설정하는 방식으로 개선
함수를 호출: Cross-cutting Concern을 먼저 실행하고, Core Concern을 실행해서 결과를 호출하는 방식

 




- 2강 AOP 자바 코드 이해
spring을 사용하지 않았을 때

public class NewlecExam implements Exam {
	public int total() {
		보조 로직 1
		주 로직 
		보조 로직 2
	}
}


보조로직과 주 로직을 분리
Core Concern

public class NewlecExam implements Exam {
	public int toal() {
		주 로직
	}


Cross-cutting Concern

보조 로직1

보조 로직2



proxy 개념 사용 : 주 업무를 호출하는 기능, 사용자는 proxy를 호출하고, proxy에서 보조 로직을 삽입
※ proxy : '가짜'의 뜻을 가지고 있다.
proxy의 삽입, 삭제, 수정의 문제를 spring DI로 해결

 


- 3강 순수 자바로 AOP 구현 

public class Program {
  public static void main(String[] args) {

  // 주 로직
  Exam exam = new NewlecExam(1, 1, 1, 1);
		
  // 보조 로직
  Exam proxy = (Exam) Proxy.newProxyInstance(NewlecExam.class.getClassLoader(), 
						new Class[]{Exam.class},
						new InvocationHander() {
  // Proxy.newProxyInstance(load, interfaces, h)

	
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) {
			
		long start = System.currentTimeMillis();

		Object result = method.invoke(exam, args);
		// invoke(obj, args): obj: 실제 업무. args: 호출할 수 있는 메서드가 담는 파라미터를 갖는 곳 
			
		long end = System.currentTimeMillis();
		String message = (end - start) + "ms 시간이 걸렸습니다.";

		System.out.println(message);  

		return result;
		}
	}
	);

	system.out.printf("total is %d\n", proxy.total());
	system.out.printf("avg is %d\n", proxy.avg());
	}	
}

proxy를 통해 보조 로직을 수행할 수 있다.
Proxy.newProxyInstance의 매개변수로 load, interfaces, h가 필요


- 4강 : 스프링으로 AOP 구현, AroundAdvice

  • Before : 앞에만 처리
  • After returnning : 뒤에만 처리
  • After throwing : 예외가 발생했을 때 처리
  • Around : 앞 뒤로 처리

 

setting.xml에서 코드 작성.. 



- 5강 BeforeAdvice 구현



- 6강 After Returnning / Throwing Advice
after returnning :  implements 
Throwing : implements ThrowsAdvice

다음시간 : 원하는 메서드 몇개만 골라서 설정하는 방법

 


- 7강 포인트컷, 조인 포인트, 위빙

주업무와 보조업무를 뜨게질하는 것과 같이 엮어 주는것

proxy는 Core Concern의 모든 주 업무를 조인 포인트로 생각하고 위빙한다. 
일부 주 업무 기능만 보조 업무와 엮어주는 것을 포인트 컷이라고 한다. 

<bean id="classicPointCut" class="org.springframework.aop.support.NameMatchMethodPoint">
  <property name="mappedName" value="total" />
<bean>

<bean id="classicBeforeAdvisor" class="org.springframwork.aop.support.DefaultPointcut">
  <property name="advice" ref="logBeforeAdvice" / >
  <property pointcut" ref="classicPointCut" />
</bean>

<bean id="classicAroundAdvisor" class="org.springframwork.aop.support.DefaultPointcut">
  <property name="advice" ref="logAroundAdvice" / >
  <property pointcut" ref="classicPointCut" />
</bean>



포인트 컷을 설정할 때마다(=advise 하나당) advisor 태그를 하나씩 만들어야 한다는 부담이 있다. 
다음 강의에서는 이를 편하게 만드는 법을 배운다. 그 이후에는 어노테이션으로 더욱 더 쉬운 방법을 배울 예정


- 8강 : 간소화된 Advisor
advisor 와 포인트 컷을 합쳐서 간소화 시키고 싶다면!
advisor 중에서 포인트 컷 기능을 내재하고 있는 코드를 활용

합치기 전 코드 

<bean id="classicPointCut" class="org.springframework.aop.support.NameMatchMethodPointcut">
  <property name="mappedName" value="total" />
<bean>

<bean id="classicBeforeAdvisor" class="org.springframwork.aop.support.DefaultPointcut">
  <property name="advice" ref="logBeforeAdvice" / >
  <property pointcut" ref="classicPointCut" />
</bean>


합쳤을 때 코드

<bean id="classicBeforeAdvisor" class="org.springframwork.aop.support.NameMatchMethodPointcutAdvisor">
  <property name="advice" ref="logBeforeAdvice" / >
  <property name="mappedName" value="total"></property>
</bean>



정규식을 사용하는 RegexpMethodPointcut도 사용할 수 있다.
list 태그 안의 value 태그의 이름이 정규식을 따라가도록 한다.

 

 

 

 

'Spring' 카테고리의 다른 글

[Spring] 뉴렉처 스프링 프레임워크 강의 필기  (0) 2022.06.16
[Spring] 스프링 vs 스프링 부트  (0) 2022.05.03