Điều này có thể dễ dàng thực hiện với một số ApplicationListener
. Tôi có này để làm việc nghe Spring 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
}
}
nghe Ứng dụng chạy đồng bộ trong mùa xuân. Nếu bạn muốn chắc chắn rằng mã của bạn chỉ được thực hiện một lần, chỉ cần giữ một số trạng thái trong thành phần của bạn.
CẬP NHẬT
Bắt đầu với mùa xuân 4.2 trở lên, bạn cũng có thể sử dụng @EventListener
chú thích để quan sát ContextRefreshedEvent
(nhờ @bphilipnyc cho trỏ này ra):
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
}
}
Nguồn
2013-06-11 06:26:49
mẹo là gì với @Scheduled? đó là chính xác những gì tôi muốn! – chrismarx