[Spring] AOP (관점 지향 프로그래밍)

seonjeong·2023년 2월 25일
0

Spring

목록 보기
8/27
post-thumbnail

💖 AOP란?

  • Aspect Oriented Programming
  • 목적 : 감시자
  • 어떤 로직을 기준으로 핵심적인 관점, 부가적인 관점으로 나누어서 보고 관점을 기능을 기준으로 각각 모듈화 -> 코드를 부분적으로 나누어 모듈화

핵심적인 관점 : 핵심 비즈니스 로직
부가적인 관점 : 핵심 로직을 실행하기 위해 행해지는 데이터베이스 연결, 로깅, 피일 입출력 등

🔥 주요 개념

  • Aspect : 흩어진 관심사를 모듈화한 것. 주로 부가기능을 모듈화

  • Target : Aspect를 적용하는 곳(클래스, 메소드..)

  • Advice : 실질적으로 어떤 일을 해야하는 지를 담은 구현체

  • JointPoint : Advice가 적용될 위치, 끼어들 수 있는 지점. 다양한 시점에 적용 가능

  • PointCut : JointPoint의 상세한 스펙을 정의


💖 이용방법

🔥 라이브러리 추가

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.25</version>
</dependency>

🔥 web.xml

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet 
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        /WEB-INF/spring/servlet-context.xml
        /WEB-INF/spring/aop-context.xml		<!-- 설정 파일 추가 -->
      </param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>

🔥 AOP설정 : aop-context

<?xml version="1.0" encoding="UTF-8"?>
<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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
		
	<aop:aspectj-autoproxy />
	
	<!-- aop 해당 클래스를 생성 -->
	<bean id="myAop" class="mul.cam.a.aop.AopProc" />
</beans>

🔥 AOP 클래스 생성

@Aspect : 이 클래스가 'Aspect'임을 나타냄
@Component : 스프링 빈으로 등록
@Around : 타겟 메소드를 감싸서 특정 Advice를 실행한다는 의미

@Aspect
public class AopProc {

	// controller뿐만 아니라 모든 dao 감시
	@Around("within(mul.cam.a.controller.*) or within(mul.cam.a.dao.*.*)")	
	public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
		
		// session check
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
		if(request != null) {
			HttpSession session = request.getSession();
			MemberDto login = (MemberDto)session.getAttribute("login");
			if(login == null) {
				return "redirect:/sessionOut.do";
			}
		}
		
		// logger
		String signatureStr = joinpoint.getSignature().toShortString();
		
		try {
			Object obj = joinpoint.proceed();	// 실행시(controller 진입시)
			
			System.out.println("Aop log: " + signatureStr + " 메소드 실행 " + new Date());
			
			return obj;
		} finally {
			// System.out.println("실행후:" + System.currentTimeMillis());
		}
	}
}



Reference

https://engkimbs.tistory.com/746

profile
🦋개발 공부 기록🦋

0개의 댓글

관련 채용 정보