Można to łatwo zrobić za pomocą ApplicationListener
. Dostałem to do pracy słuchając wiosennego ContextRefreshedEvent
:
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class StartupHousekeeper implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
// do whatever you need here
}
}
słuchacze aplikacji uruchamiane synchronicznie na wiosnę. Jeśli chcesz się upewnić, że kod jest wykonywany tylko raz, po prostu zachowaj pewien stan w swoim komponencie.
UPDATE
Począwszy od wiosny wersji 4.2 lub nowszej można również użyć @EventListener
adnotacji przestrzegać ContextRefreshedEvent
(dzięki @bphilipnyc za wskazanie na to uwagę):
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class StartupHousekeeper {
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
// do whatever you need here
}
}
jaka jest sztuczka z @Scheduled? właśnie tego chcę! – chrismarx