메뉴 건너뛰기

조회 수 6200 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

먼저 스프링에서 AOP를 구현하는 방법은 3가지 입니다.

1. xml을 이용한 방법

2. Annotaion을 이용한 방법

3. AOP API를 이용하는 방법(요즘 이용도가 떨어짐)


저는 xml을 이용한 방법 Annotation을 이용한 방법을 포스팅 해보겠습니다. 


web.xml 설정

ApplicationContext 빈 설정

1
2
3
4
<context-param>   <param-name>contextConfigLocation</param-name>
     <!--빈 설정 파일들간에 구분은 줄바꿈(\n),컴마(,),세미콜론(;)등으로 한다.-->
    <param-value>classpath*:spring/*-context.xml</param-value>
  </context-param>




그리고 transaction-context.xml 파일을 생성하였습니다. 





라이브러리 설정
그리고 라이브러리들을 사용하기위해 aop, context, tx를 선언하였습니다. tx는 트랜잭션을 이용하기위해 선언하였으므로 굳이 안적으셔도 됩니다! 
1
2
<!--?XML:NAMESPACE PREFIX = "[default] http://www.springframework.org/schema/beans" NS = "http://www.springframework.org/schema/beans" /--><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:tx="http://www.springframework.org/schema/tx" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
</beans>
그리고 대부분 Controller를 빈을 등록하기 때문에 Service와 Repository를 빈으로 등록 시켜야 합니다.
1
2
3
4
<!--?xml:namespace prefix = "context" /--><context:component-scan base-package="lee">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"></context:include-filter>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"></context:include-filter>
              </context:component-scan>
먼저 id="aopTest" 인 빈을 등록합니다.
1
2
3
<bean class="lee.test.spring.aop.XmlAopTest" id="aopTest"><aop:config><aop:aspect ref="aopTest"><aop:pointcut id="xmlPointCut" expression="execution(* lee..*Impl.*(..))"><aop:around pointcut-ref="xmlPointCut" method="aroundAOP"><aop:before pointcut-ref="xmlPointCut" method="breforeAOP"><aop:after pointcut-ref="xmlPointCut" method="afterAOP"><aop:after-returning pointcut-ref="xmlPointCut" method="afterReturningAOP" returning="retValue"><aop:after-throwing pointcut-ref="xmlPointCut" method="afterThrowing" throwing="ex"> <!-- Advice : E -->
    </aop:after-throwing></aop:after-returning></aop:after></aop:before></aop:around></aop:pointcut></aop:aspect>
  </aop:config></bean>
위의 소스내용을 보면 
<aop:config>: aop를 정의합니다. 
<aop:aspect ref="aopTest">: aop의 대상객체를 설정합니다. 
<aop:pointcut id="xmlPointCut" expression="execution(* lee..*Impl.*(..))"/> : 포인트컷을 설정합니다. 저는 포인트컷을 '어디에서 작동할 것인가' 라고 이해하고 있습니다.
<!-- Advice : S --> : 여기부터는 Advice를 정의합니다. Advice는 '언제 작동할 것인가'라고 이해하고 있습니다.

포인트컷의 expression 속성에 들어갈 수 있는 명시자 : execution, within, bean

execution(수식어패턴(생략가능) 리턴타입패턴 패키지패턴.클래스명패턴.메소드명패턴(argument 패턴)

ex).

execution(public * com.ktds.shk..*(..))" 

실행( public 메소드이고 모든 Return Type 가지는 com.ktds.shk. 패키지 아래의 모든 메소드.)




아래의 소스는 제가 실제 테스트 했던 소스코드 입니다.
 transaction-context.xml 에서 Advice를 선언한 내용과
밑의 자바 클래스에서 선언된 함수를 일치시켜보면 이해하는데 어려움이 없을거라고 생각합니다.

그리고 joinPoint 클래스를 이용하여 몇가지 함수에 대하여 테스트 하였습니다.
JoinPoint 를 인자값으로 받을때에는 JoinPoint 클래스를 맨 앞에 써줘야 합니다.

그리고 특히 Around 함수의 구조는 변하면 안됩니다.
public Object aroundAOP(ProceedingJoinPoint joinPoint)  throws Throwable{}
이 구조로 꼭 써주세요, Around는 로직의 실행시간을 구할 수도 있습니다.

afterReturningAOP 는 객체를 매개변수로 받을수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package lee.test.spring.aop;
 
import java.util.Arrays;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
 
public class XmlAopTest {
 
  public void breforeAOP(JoinPoint joinPoint){
    System.out.println("----------------------XML-----------breforeAOP");
   
    Class clazz = joinPoint.getTarget().getClass();
    String className = joinPoint.getTarget().getClass().getSimpleName();
    String methodName = joinPoint.getSignature().getName();
    String classAndMethod = joinPoint.getSignature().toShortString();
        
    System.out.println("#########clazz######========" + joinPoint.getTarget().getClass());
        System.out.println("########joinPoint.getTarget()#######========" + joinPoint.getTarget());
        System.out.println("########className#######========" + className);
        System.out.println("#########methodName######========" + methodName);
        System.out.println("##########joinPoint.toLongString()#####========" + joinPoint.toLongString());
        System.out.println("##########joinPoint.toShortString()#####========" + joinPoint.toShortString());
        System.out.println("##########classAndMethod#####========" + classAndMethod);
  }
 
public Object aroundAOP(ProceedingJoinPoint joinPoint)  throws Throwable{
  System.out.println("----------------------XML----함수진입------aroundAOP");
  long start = System.nanoTime();
    try {
      System.out.println("----------------------XML----해당 메소드 실행 전------aroundAOP");
     Object result = joinPoint.proceed();// 대상객체의 메서드 실행(ProceedingJoinPoint 타입은 대상 객체의 메서드를 호출할 때 사용)
     return result;
    } finally {
      System.out.println("----------------------XML----해당 메소드 실행 후------aroundAOP");
     long finish = System.nanoTime(); //1/1000000000
     Signature sig = joinPoint.getSignature(); //메서드의 시그니쳐
     System.out.printf("%s.%s(%s) 실행 시간 : %d ns\n",
       joinPoint.getTarget().getClass().getSimpleName(),
       sig.getName(), Arrays.toString(joinPoint.getArgs()),
       (finish - start)/1000000000);
      
       System.out.println("##############joinPoint.toLongString()===================" + joinPoint.toLongString()); //대상 메서드 전체 syntax 리턴
       //execution(public abstract javax.sql.DataSource com.ibatis.sqlmap.client.SqlMapTransactionManager.getDataSource())
        
       System.out.println("##############joinPoint.toShortString()===================" + joinPoint.toShortString()); // 대상 메소드명 리턴
       //execution(SqlMapTransactionManager.getDataSource())
        
       System.out.println("##############joinPoint.getTarget()===================" + joinPoint.getTarget()); //대상객체를 리턴
       //com.ibatis.sqlmap.engine.impl.SqlMapClientImpl@1dc7b3e
        
       System.out.println("##############joinPoint.getSignature()===================" + joinPoint.getSignature()); //호출되는 메소드 정보
       //DataSource com.ibatis.sqlmap.client.SqlMapTransactionManager.getDataSource()
        
       System.out.println("##############joinPoint.getTarget().getClass().getSimpleName()===================" + joinPoint.getTarget().getClass().getSimpleName());
       //SqlMapClientImpl
    }
    
}
 
public void afterAOP(){
  System.out.println("----------------------XML----------afterAOP");
}
 
//JoinPoint 는 대상 target 객체 정보를 보유한 결합지점
  //retValue 는 target 메서드가 실행한 후 return 값
public void afterReturningAOP(JoinPoint joinPoint, Object retValue){
     System.out.println("---------------XML--------------afterReturningAOP");
    String targetClass=joinPoint.getTarget().getClass().getName();
    String methodName=joinPoint.getSignature().getName();
     
    System.out.println("########logging!! className="+targetClass+"  methodName="+methodName +" retVal : "+retValue);
   
    }
 
  public void afterThrowing(Throwable ex){
    System.out.println(ex.getMessage() + " :############## @AfterThrowing");
    }
}



호출순서!






List of Articles
번호 제목 날짜 조회 수
38 쿠팡 api 프로젝트 / 적용 테스트 (스프링 부트 / 자바 ) file 2021.03.29 550
37 쿠키와 세션을 이용한 자동 로그인 처리 file 2018.07.04 8970
36 자바 스프링프레임워크 개발환경 설정하기-2편 file 2016.08.18 6490
35 자바 스프링프레임워크 개발환경 설정하기-1편 file 2016.08.18 6839
» 자바 스프링, spring AOP 구현 (xml 방식) file 2016.08.18 6200
33 자바 스프링, spring AOP 구현 (xml 방식) file 2016.08.18 5892
32 스프링을 구성하는 코어 모듈 - core module file 2016.12.08 5119
31 스프링에서 구글맵 연동하기 2018.07.04 4577
30 스프링과 안드로이드 연동5 : (Javascript에서 Android 함수 호출하기) 2018.07.04 3389
29 스프링과 안드로이드 연동4 : (JSON으로 가져오기) file 2018.07.04 5529
28 스프링과 안드로이드 연동3 : ( 서버에서 XML로 반환해 가져오기 ) 2018.07.04 2895
27 스프링과 안드로이드 연동2 : 서버에서 안드로이드로 이미지 가져오기(다운) 2018.07.04 3312
26 스프링과 안드로이드 연동1(Html 소스 가져오기) 2018.07.04 2674
25 스프링, MySQL, MyBatis 연동 - 데이터 조회하기 file 2021.05.06 785
24 스프링, MySQL, MyBatis 연동 file 2021.05.06 127
23 스프링(spring) 메일 발송 :: mailSender 2016.08.18 14879
22 스프링 프로젝트 생성 후 샘플 코드 한글 깨짐 현상 file 2021.03.31 185
21 스프링 외부 경로 폴더 지정하기 2018.07.04 4608
20 스프링 XML 설정에서 자바 설정 Import하기 file 2016.08.18 5071
19 스프링 Bean 객체의 초기화 및 소멸시 호출 메서드 file 2016.08.18 4996
Board Pagination Prev 1 2 Next
/ 2

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved