๐Ÿ“˜ Web/Spring, JPA

[Spring] AOP ์‚ฌ์šฉ ์˜ˆ์ œ - AOP class ๊ตฌํ˜„

a n u e 2022. 3. 24. 21:27

AOP๋Š” IOC, DI, DL๊ณผ ๋”๋ถˆ์–ด ์Šคํ”„๋ง์˜ ๋Œ€ํ‘œ์ ์ธ ํŠน์„ฑ์ด๋‹ค.

๊ฐ„๋‹จํ•˜๊ฒŒ ๋งํ•˜์ž๋ฉด, ๊ณตํ†ต์ ์ธ ์š”์†Œ๋‚˜ ๋ฐ˜๋ณต๋˜์–ด ์‚ฌ์šฉ๋˜๋Š” ์š”์†Œ๋ฅผ ํ•œ ๊ณณ์— ๋ฌถ์–ด ๊ด€๋ฆฌํ•˜๋Š” ๊ด€์  ์ง€ํ–ฅ์  ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ธฐ๋ฒ•์ด๋ผ ํ•  ์ˆ˜ ์žˆ๋‹ค.


method๊ฐ€ ์‹คํ–‰๋ ๋•Œ๋งˆ๋‹ค

method์˜ parameter์™€ method return value๋ฅผ console์— ์ฐ๋Š” AOP๋ฅผ ๊ตฌํ˜„ํ•ด๋ณด์ž

(๊ธฐ์กด์— ๊ฐœ์ธ์ ์œผ๋กœ ๊ณต๋ถ€ํ•˜๋˜ ํ”„๋กœ์ ํŠธ์— ๋„ฃ์–ด๋ณด์•˜๋‹ค)

 

๊ทธ ์ „์—ใ…กํ•ด๋‹น ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜๋ ค๋ฉด, AOP ๊ธฐ๋Šฅ๊ณผ ๊ด€๋ จ๋œ ์Šคํ”„๋ง annotaion์— ๋Œ€ํ•ด ์•Œ์•„์•ผํ•œ๋‹ค.

@Aspect AOP ํด๋ž˜์Šค ์ •์˜ ์‹œ ์‚ฌ์šฉ
@Pointcut AOP ๊ธฐ๋Šฅ์„ ์ง€์ •ํ•˜๊ธฐ ์œ„ํ•œ ๋ฒ”์œ„๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค
@Before ๋ฉ”์†Œ๋“œ ์‹คํ–‰ ์ „
@After ๋ฉ”์†Œ๋“œ ์‹คํ–‰(์„ฑ๊ณต) ํ›„
@AfterReturning ๋ฉ”์†Œ๋“œ๊ฐ€ ์ •์ƒ ์ข…๋ฃŒ ์‹œ
@AfterThrowing ๋ฉ”์†Œ๋“œ์—์„œ ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ

 

 

servlet-context.xml

 

 

root-context.xml

 

 

ParamAop Class ์ƒ์„ฑ

 

package com.shop.controller;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ParamAop {
	
	//ํ•ด๋‹น ํŒจํ‚ค์ง€ ํ•˜์œ„ ํด๋ž˜์Šค ์ „๋ถ€ ์ ์šฉ
	@Pointcut("execution(* com.shop.controller..*.*(..))")
	private void paramCall() {}
	
	/* JoinPoint interface
	 * ํด๋ผ์ด์–ธํŠธ๊ฐ€ ํ˜ธ์ถœํ•œ ๋น„์ง€๋‹ˆ์Šค์˜ ๋ฉ”์„œ๋“œ ์ •๋ณด๋ฅผ ์•Œ๊ธฐ ์œ„ํ•œ ์ธํ„ฐํŽ˜์ด์Šค
	 */
	//paramCall method ์‹คํ–‰ ์ „์— ์‹คํ–‰ํ•˜๋Š” method๋ผ๋Š” ์˜๋ฏธ
	@Before("paramCall()")
	public void before(JoinPoint joinPoint)
	{
		//method ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ๋‹ด๋Š”๋‹ค
        Object[] args = joinPoint.getArgs();
		
        //๋งค๊ฐœ๋ณ€์ˆ˜ ๋ฐฐ์—ด์˜ ์ข…๋ฅ˜ ๋ฐ ๊ฐ’ ์ถœ๋ ฅ
        for(Object obj : args) {
            System.out.println(" ์ปจํŠธ๋กค๋Ÿฌ ๋งค๊ฐœ๋ณ€์ˆ˜ ํƒ€์ž…์„ ์•Œ๋ ค์ค˜ : " + obj.getClass().getSimpleName());
            System.out.println(" ์ปจํŠธ๋กค๋Ÿฌ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐ’์„ ์•Œ๋ ค์ค˜ : " + obj);
        }
    }

	//paramCall method๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด afterReturn method๋ฅผ ์‹คํ–‰์‹œ์ผœ์ค˜
	//@AfterReturning ์–ด๋…ธํ…Œ์ด์…˜์˜ returning ๊ฐ’๊ณผ afterReturn ๋งค๊ฐœ๋ณ€์ˆ˜ obj์˜ ์ด๋ฆ„์ด ๊ฐ™์•„์•ผ ํ•จ
	@AfterReturning(value = "paramCall()", returning = "obj")
	public void afterReturn(JoinPoint joinPoint, Object obj) {
        System.out.println(" ์ปจํŠธ๋กค๋Ÿฌ์—์„œ Return๋˜๋Š” ๊ฐ’์„ ์•Œ๋ ค์ค˜ : " + obj);
    }
}

 

 

AOP๊ฐ€ ์‹คํ–‰๋œ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

 


References

https://programforlife.tistory.com/107