SPRING/스프링프레임워크 핵심개념
스프링 AOP: @AOP
JUMP개발자
2021. 5. 29. 17:12
Spring AOP를 시작하기 위해서는 아래와 같이 의존성을 추가해야 한다.
<dependency>
<groupId>org.spring.framwork.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Aspect을 통해 Aspect로 정의하고 Component 등록을 한다.
@Component
@Aspect
public class PerfAspect {
// 1. com.springaop로 시작하는 패키지의 EventService 클래스의 모든 메서드에 적용
//@Around("execution(* com.springaop..*.EventService.*(..))")
// 2. 아래 PerfLogging 어노테이션이 적용된 곳만 적용
@Around("@annotation(PerfLogging)")
// 3. 해당 Bean의 모든 메서드에 적용
// @Around("bean(simpleEventService)")
public Object logPerf(ProceedingJoinPoint pjp) throws Throwable {
long begin = System.currentTimeMillis();
Object retVal = pjp.proceed();
System.out.println(System.currentTimeMillis() - begin);
return retVal;
}
// simpleEventService의 모든 Method 실행 전에 hello method가 실행
@Before("bean(simpleEventService)")
public void hello() {
System.out.println("hello");
}
}
@Service
public class SimpleEventService implements EventService {
// PerfLogging 어노테이션이 붙은 메서드만 Aspect에 등록된 Advice를 실행
@PerfLogging
@Override
public void createEvent() {
long begin = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Created an event");
}
@PerfLogging
@Override
public void publishEvent() {
long begin = System.currentTimeMillis();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Published an event");
}
@PerfLogging
@Override
public void deleteEvent() {
System.out.println("Delete an event");
}
}
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
// Retention은 아래 Annotation을 얼마나 유지할 것인가를 의미
// CLASS file까지 Annotation 정보를 유지 (일반적으로)
public @interface PerfLogging {
}
어드바이스 정의
- @Before
- @AfterReturning
- @AfterThrowing
- @Around