스프링 AOP
Last updated
Last updated
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
EventService eventService;
@Override
public void run(ApplicationArguments args) throws Exception {
eventService.createEvent();
eventService.publishEvent();
}
}public interface EventService {
void createEvent();
void publishEvent();
}@Service
public class SimpleEventService implements EventService {
// 이 코드는 건드리지 않고 시간을 측정하려 한다.
@Override
public void createEvent() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Created an event");
}
@Override
public void publishEvent() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Published an event");
}
}// AppRunner는 이 빈을 먼저 불러와 실행한다.
@Primary
@Service
public class ProxySimpleEventService implements EventService {
@Autowired
SimpleEventService simpleEventService;
// 부가 기능은 여기서 적용한다.
@Override
public void createEvent() {
long begin = System.currentTimeMillis();
simpleEventService.createEvent();
System.out.println(System.currentTimeMillis() - begin);
}
@Override
public void publishEvent() {
long begin = System.currentTimeMillis();
simpleEventService.publishEvent();
System.out.println(System.currentTimeMillis() - begin);
}
}<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>@Component
@Aspect
public class PerfAspect {
@Around("execution(* me.gracenam..*.EventService.*(..))")
public Object logPerf(ProceedingJoinPoint pjp) throws Throwable {
long begin = System.currentTimeMillis();
Object retVal = pjp.proceed();
System.out.println(System.currentTimeMillis() - begin);
return retVal;
}
}