본문 바로가기
매일코딩/Spring

25.스프링프로젝트 - aop

by 인생여희 2016. 11. 17.
반응형

AOP ( Aspect Oriented Programming , 관점(관심) 지향적인 프로그래밍 )


- OOP(Object Oriented Programming, 객체지향프로그래밍)를 보완하는 확장적인 개념


- Aspect(측면, 관점, 관심) : 핵심적인 비즈니스 로직은 아니지만 반드시 해야 하는 작업들



- 관심의 분리(Separation of Concerns)를 통해 핵심관점(업무로직) + 횡단관점(트랜잭션,로그,보안,



인증 처리 등)으로 관심의 분리를 실현

- 장점 : 중복되는 코드 제거, 효율적인 유지 보수, 높은 생산성, 재활용성 극대화, 변화 수용의 용이성



* AOP의 주요 용어


- Aspect :  공통 관심사(로깅, 보안, 트랜잭션 등)


- Join Points : method를 호출하는 시점, 예외가 발생하는 시점 등과 같이 특정 작업이 실행되는 시점을 의미함


- Advice : Join Points에서 실행되어야 하는 코드(실제로 AOP 기능을 구현한 객체)


- Pointcuts : 실제로 Advice를 적용시킬 대상 method


- Proxy : Advice가 적용되었을 때 만들어지는 객체


* Advice의 종류


- Before : target method 호출 전에 적용


- After : target method 호출 후에 적용


- Around : target method 호출 이전과 이후 모두 적용(가장 광범위하게 사용됨)




contents from : http://edu.lifesoft.org/board/show.aspx?category=spring&idx=370&page=0


1. needs file


pom.xml


1
2
3
4
5
6
7
    <!-- aop 지원 라이브러리 -->
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
cs



2. root-context.xml

. root-context.xml의 Namespace에 aop 추가


1
2
3
4
5
6
        //root-context.xml
        
        xmlns:aop="http://www.springframework.org/schema/aop"
        
        //    <!-- 관점 지향 aop 태그/ 반드시 컴포넌트 스켄 위에 넣어야 한다 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
cs



3.advice


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
 
package com.example.web03.aop;
 
import java.util.Arrays;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import com.example.web03.controller.board.BoardController;
 
//종단 관심 - 핵심적인 비즈니스 로직
//횡단관심(aspect) 공통적인 로직 (로그, 트랜젝션 등등)
// Advice - 횡단관심을 모든 코드에서 처리하지 않고 공통적으로 처리 할 수 있도록 지원하는 코드
 
@Component // 스프링에서 관리하는 빈
@Aspect // 스프링에서 관리하는 aop bean
 
public class LogAdvice {
    // 포인트컷 - 실행 시점, around 실행 전후
    // 컨트롤러의 모든 method 실행 전후에 logPrint method가 호출됨
 
    // 로거 변수 만들기
    private static final Logger Logger = LoggerFactory.getLogger(LogAdvice.class);
 
    @Around("execution(* com.example.web03.controller..*Controller.*(..))"
            + " or execution(* com.example.web03.service..*Impl.*(..))"
            + " or execution(* com.example.web03.model..*Impl.*(..))")
    public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable {
 
        // 현재 시스템의 시간
        long startTime = System.currentTimeMillis();
 
        // 컨트롤러의 method가 실행됨
        Object result = joinPoint.proceed();
 
        // 클래스 이름
        String type = joinPoint.getSignature().getDeclaringTypeName();
        // method 이름
        String method = joinPoint.getSignature().getName();
        // 매개변수
        String args = Arrays.toString(joinPoint.getArgs());
 
        /*
         * System.out.println("클래스" + type); System.out.println("method" +
         * method); System.out.println("매개변수" + args);
         */
        // 로깅 툴을 이용한 로거 찍기
 
        Logger.info("클래스=" + type);
        Logger.info("method=" + method);
        Logger.info("매개변수=" + args);
 
        long endTime = System.currentTimeMillis();
 
        Logger.info("실행시간=" + (endTime - startTime));
        Logger.info("=================================================");
        /*
         * System.out.println("실행시간" + (endTime - startTime));
         * System.out.println(
         * "=================================================");
         */
        return result;
    }
}
 
cs



반응형

'매일코딩 > Spring' 카테고리의 다른 글

27.springproject - log  (4) 2016.11.18
26.스프링프로젝트 - 페이징 처리  (6) 2016.11.17
24.스프링프로젝트 - download  (0) 2016.11.17
23.스프링프로젝트 - board write  (0) 2016.11.17
22.spring board list  (0) 2016.11.17

댓글