@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);
}
}
문제점
매번 프록시 클래스를 작성해야 한다.
여러 클래스 여러 메서드에 적용하려면 복잡해진다.
스프링 AOP
이런 문제를 해결하기 위해 등장했다.
스프링 IoC 컨테이너가 제공하는 기반 시설과 Dynamic 프록시를 사용해 복잡한 문제를 해결한다.