본문 바로가기

Programming!

Spring @Async 사용하기.


xxxx-application.xml

<beans xmlns="http://www.springframework.org/schema/beans"

....

xmlns:task="http://www.springframework.org/schema/task"

....

xsi:schemaLocation="....http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd....

>


<task:annotation/>


</beans> 



Async Component

@Component

public class NotificationComponent {


private Logger logger = LoggerFactory.getLogger(this.getClass());


@Async

public void add() {

logger.debug("Async Add() 를 실행합니다. Thread Sleep 5000");

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

logger.debug("Async Add() 가 종료되었습니다.");

}

}




Service

@Service

public class NotificationService {


private Logger logger = LoggerFactory.getLogger(this.getClass());


@Autowired

private NotificationComponent notificationComponent;


public void add() {

logger.debug("Async Method 호출 시작 ");

notificationComponent.add();

logger.debug("Async Method 호출 종료 ");  

}


}





당연히 Service의 'Async Method 호출 종료'가 먼저 찍히고 이후 'Async Add() 가 종료 되었습니다.' 가 찍힐것이다. 
(뭐 당연하겠지...)