
AOP는 스프링에서 빈 후처리기(Bean Post Processor)를 통해 적용됩니다. 객체를 빈으로 등록할 때 해당 객체를 프록시로 감싸는 방식으로 AOP를 적용합니다. AOP 적용 후에는 프록시 객체가 실제로 호출되며, 이를 통해 부가기능이 실행됩니다.
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class ExecutionTimeAspect {
// 포인트컷: 서비스 레이어의 모든 메서드에 적용
@Pointcut("execution(* com.example.demo.service..*(..))")
public void serviceLayer() {}
// 어드바이스: 메서드 실행 전후에 걸쳐 시간을 측정하는 로직
@Around("serviceLayer()")
public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis(); // 시작 시간 측정
try {
// 메서드 실행
Object result = joinPoint.proceed();
return result;
} finally {
// 종료 시간 측정 및 실행 시간 출력
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
log.info("Method {} executed in {}ms", joinPoint.getSignature(), executionTime);
}
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
@Bean
public ExecutionTimeAspect executionTimeAspect() {
return new ExecutionTimeAspect();
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CourseService {
public String createCourse(String courseName) {
// 실제 비즈니스 로직: 수업 생성
log.info("Course {} is being created...", courseName);
return "Course created: " + courseName;
}
}
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class CourseController {
private final CourseService courseService;
@GetMapping("/course/create")
public String createCourse(@RequestParam String name) {
return courseService.createCourse(name);
}
}