울음참고 개발공부
Published 2025. 2. 4. 16:07
AOP 동작 방식 Spring & Spring Boot
728x90

 

 

AOP(Aspect-Oriented Programming) 가 프록시 기반으로 동작하는 원리 

 

 

- AOP 는 Spring의 프록시 기반 방식으로 동작하기 때문에 @Controller 이든 @RestController 이든 @Component 이든 Spring이 관리하는 Bean 이면 적용된다.

 

@Controller vs @RestController 차이점
- @Controller : 주로 View(HTML,JSP) 반환하는 MVC 컨트롤러
- @RestController : JSON 데이터를 반화하는 REST API 컨트롤러(@ResponseBody 가 기본 적용)

 

 

동작 예시 )

 

[ AOP 적용 전 ]

@Service
public class SampleService {
	public void doSomething() {
    	System.out.println("DO SOMETHING !!!");
    }
}

 

 

[ AOP 적용 후 ]

public class SampleServiceProxy extends SampleService {
	private SampleService target;
    
    public SampleServiceProxy(SampleService target) {
    	this.target = target;
    }
    
    @Override
    public void doSomething() {
    	System.out.println("AOP 실행 전");
        target.doSomething(); // 원래의 비즈니스 로직 실행 
        System.out.println("AOP 실행 후");
    }
}

 

 

Spring AOP 는 SampleService 객체를 감싸는 프록시 객체(SampleServiceProxy)를 자동으로 만들어서 대신 실행하도록 함

 

 

 

AOP 사용을 위한 필수 어노테이션 @Aspect 와 @Component

 

1) @Aspect 

  • 이 클래스가 AOP 기능을 포함하고 있음을 알리는 역할
  • @Around, @Before, @After 같은 AOP 관련 어노테이션을 사용할 수 있도록 함

 

2) @Component

    : Spring이 이 클래스를 Bean으로 등록하도록 하는 역할

     => Spring이 객체를 생성해서 관리하도록 함으로써 AOP 가 적용될 수 있게 함 

 

@Component 를 생략하면 Spring이 이 클래스(Aspect)를 인식하지 못해서 AOP 가 동작하지 않는다. 

 

 

 

 

@Around와 ProceedingJoinPoint를 활용한 AOP 로그 예제 )

@Aspect
@Component
public class LoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    @Around("execution(* com.example.service.*.*(..))")  // 모든 Service 메서드에 적용
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed(); // 원래 메서드 실행

        long executionTime = System.currentTimeMillis() - start;
        logger.info("[AOP LOG] {} 실행 시간: {}ms", joinPoint.getSignature(), executionTime);

        return result;
    }
}

 

 

 AOP 관련 어노테이션 간단 정리
어노테이션 설명
@Before 메서드 실행 에 실행됨
@After 메서드 실행 에 실행됨
@AfterReturning 메서드가 정상적으로 실행된 후에 실행됨
@AfterThrowing 메서드 실행 중 예외가 발생했을 때 실행됨
@Around 메서드 실행 전후 모두 제어 가능 (ProceedingJoinPoint 사용)

 

 

 


 

 

@ EnableAspectJAutoProxy - Spring Boot / Spring 에서 사용할 때 차이점 

 

 

@ EnableAspectJAutoProxy

: Spring 에서 AOP 기능을 활성화할 때 사용

 

 

[ Spring Boot ]

  • spring-boot-starter-aop 의존성을 포함하면 자동으로 AOP를 설정
  • 따라서 별도로 선언하지 않아도 AOP 가 동작함 

 

[ Spring ]

  • 순수 Spring Framework 를 사용할 때는 @EnableAspectJAutoProxy 를 직접 설정해야 AOP 가 동작함 
  • 예시 ) 
@Configuration
@EnableAspectJAutoProxy
	public class AppConfig {
}

 

 

 

 

 

### AOP 관련 포스팅 

 

https://blog.naver.com/megaki-log/222972951526?trackingCode=blog_bloghome_searchlist

 

AOP(1)

AOP 사용이유 ) - 해당 로직은 등록을 위함이다 - BindingResult 로 유효성검사에서 잡힌 에러를 출력...

blog.naver.com

https://blog.naver.com/megaki-log/222973017052?

 

AOP(2)

[ 어노테이션 생성하여 AOP 사용하기 ] annotation 생성 AOP 에 Pointcut 추가 - aop 에 @Pointcut...

blog.naver.com

 

728x90
profile

울음참고 개발공부

@메각이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!