메뉴 건너뛰기

조회 수 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");
    }
}



호출순서!






  1. 스프링(spring) 메일 발송 :: mailSender

    Date2016.08.18 Views14879
    Read More
  2. play framework + 이클립스 초간단 개발환경 구축법

    Date2016.12.08 Views12384
    Read More
  3. 쿠키와 세션을 이용한 자동 로그인 처리

    Date2018.07.04 Views8970
    Read More
  4. 루씬 기본적인 검색 엔진 - 샘플 예제

    Date2016.12.08 Views7768
    Read More
  5. 자바 스프링프레임워크 개발환경 설정하기-1편

    Date2016.08.18 Views6839
    Read More
  6. 자바 스프링프레임워크 개발환경 설정하기-2편

    Date2016.08.18 Views6490
    Read More
  7. 검색엔진 (2) - 라이브러리: Lucene, Solr, Elasticsearch

    Date2016.12.08 Views6228
    Read More
  8. 자바 스프링, spring AOP 구현 (xml 방식)

    Date2016.08.18 Views6200
    Read More
  9. 검색엔진 (1) - 검색엔진의 이해

    Date2016.12.08 Views6032
    Read More
  10. [펌]자바 Crawling(크로울링) 로그인 해 긁어오기

    Date2018.07.04 Views5982
    Read More
  11. [패스트캣]1. 시작하기 - 설치

    Date2016.12.08 Views5981
    Read More
  12. Nutch 0.9 를 이용하여 한글 검색하기

    Date2016.12.08 Views5928
    Read More
  13. 자바 스프링, spring AOP 구현 (xml 방식)

    Date2016.08.18 Views5892
    Read More
  14. 스프링 2.5.2 설치및 HelloWorld 출력하기

    Date2016.12.06 Views5836
    Read More
  15. 스프링 AOP의 주요 용어

    Date2016.08.18 Views5829
    Read More
  16. solr적용시 사용법

    Date2016.12.08 Views5582
    Read More
  17. Spring Security Basic 인증 비활성화 설정

    Date2016.08.18 Views5556
    Read More
  18. 스프링과 안드로이드 연동4 : (JSON으로 가져오기)

    Date2018.07.04 Views5529
    Read More
  19. Spring 개발을 위한 Eclipse 개발 환경 구성하기

    Date2016.12.06 Views5431
    Read More
  20. Spring Framework 개요

    Date2016.12.08 Views5339
    Read More
Board Pagination Prev 1 2 Next
/ 2

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved