SPRING #5 - AOP

김형우·2022년 4월 4일
0

Spring #2

목록 보기
5/8

AOP

  • 되돌아 올수 있도록 url 정보를 세션에 저장
  • 로그인 후 다시 돌아오기 위함
  • 이걸 모든페이지에 다 넣을래? ㄴㄴ
  • 그래서 스프링 기능 사용
  • 컨트롤러로 진입하는 통로에 해당 코드를 짜넣는다.
  • 컨트롤러 진입하는 통로 = 필터개념
  • 컨트롤러로 진입할건데 이런이런 컨트롤러는 이런 필터를 거쳐서 진입하세요 같은거

0. 라이브러리 설정

0-1. pom.xml

  • 라이브러리 추가
<!-- aop -->
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

0-2. Boot20220328Application.java

@EnableAspectJAutoProxy // aop추가
// 컨트롤러, 환경파일, 서비스(mybatis 1버전용)
@ComponentScan(basePackages = {
		"com.example.controller",
		"com.example.service",
		"com.example.config",
		"com.example.aop", // aop추가
		"com.example.interceptor"
})

1. 사용

1-1. /aop/LogAspect.java

  • 로그용도로 사용
  • 개발의 편리성을 위함
  • 공통적인 작업을 구현하기위한 용도
  • 패키지가 com.example.controller인 컨트롤러는 모두 수행
  • or을 이용해서 mapper도 똑같이 사용 가능
  • 어느 컨트롤러에 어느 매퍼를 사용하는지 추적가능
package com.example.aop;

// import javax.servlet.http.HttpServletRequest;
// import javax.servlet.http.HttpSession;

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 org.springframework.web.context.request.RequestContextHolder;
// import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class LogAspect {

    // 로그용도로 사용
    // 개발의 편리성을 위함
    Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // 공통적인 작업을 구현하기위한 용도
    // 패키지가 com.example.controller인 컨트롤러는 모두 수행
    // or을 이용해서 mapper도 똑같이 사용 가능
    // 어느 컨트롤러에 어느 매퍼를 사용하는지 추적가능
    // @Around("execution(* com.example.controller.*Controller.*(..))")
    @Around("execution(* com.example.controller.*Controller.*(..)) or execution(* com.example.mapper.*Mapper.*(..))")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 현재시간 보관
        long start = System.currentTimeMillis();
        // 수행되는 클래스명
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String type = "";
        if (className.contains("Controller") == true) {
            type = "Controller => ";
        } else if (className.contains("Service") == true) {
            type = "Service => ";
        } else if (className.contains("Mapper") == true) {
            type = "Mapper => ";
        }
        // 끝나는 시간
        long end = System.currentTimeMillis();

        // 메소드명
        String methodName = joinPoint.getSignature().getName();
        // 로그로 출력
        logger.info(type + className + " => " + methodName);
        logger.info("execute time => " + (end - start));

        // System.out.println("클래스명 : " + className);
        // System.out.println("메소드명 : " + methodName);
        return joinPoint.proceed();
    }
}

버전이 올라가면서 타입문제로 session에 저장은 되는데 불러오기가 작동안됨
interceptor로 대체

profile
The best

0개의 댓글