Spring MVC - 在任何人进入网页之前做某事
Spring MVC - do sth before anyone goes into webpage
我需要创建一个在夜间将数据加载到数据库中的应用程序(f.i 4a.m)。我找到了这个教程:
http://websystique.com/spring/spring-job-scheduling-with-scheduled-enablescheduling-annotations/
而且这个日程安排非常有效!但是...,为了以某种方式告诉我的应用程序它将开始使用我必须编写的调度程序:
AbstractApplicationContext context = new AnnotationConfigApplicationContext(ApplicationScheduler.class);
而且...我不知道该把它放在哪里。我不能将它放入我的控制器中,因为它将在用户进入网页时设置,并且在开始时将没有数据。所以当我在服务器上部署我的应用程序时,我需要设置这个调度程序。例如,我将我的应用程序放在 2a.m 的服务器上,然后它知道在 4a.m 它将下载数据。
综上所述,
我知道如何设置这个调度程序在我想做的时候做我想做的事。我只是不知道我应该在哪里设置这个抽象应用程序上下文。
您可以创建 f.e。一些 class 用 @Service 注释并将计划的方法放在其中。
@Service
public class SchedulerService {
@Scheduled(cron="0 4 * * * ?")
public void loadDataInDB() {
. . .
}
}
感谢您的回答,但我认为我找到了最好的答案:
public class MyAppServletContextListener
implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
}
//Run this before web application is started
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
AbstractApplicationContext context = new AnnotationConfigApplicationContext(ApplicationScheduler.class);
}
}
我需要创建一个在夜间将数据加载到数据库中的应用程序(f.i 4a.m)。我找到了这个教程: http://websystique.com/spring/spring-job-scheduling-with-scheduled-enablescheduling-annotations/
而且这个日程安排非常有效!但是...,为了以某种方式告诉我的应用程序它将开始使用我必须编写的调度程序:
AbstractApplicationContext context = new AnnotationConfigApplicationContext(ApplicationScheduler.class);
而且...我不知道该把它放在哪里。我不能将它放入我的控制器中,因为它将在用户进入网页时设置,并且在开始时将没有数据。所以当我在服务器上部署我的应用程序时,我需要设置这个调度程序。例如,我将我的应用程序放在 2a.m 的服务器上,然后它知道在 4a.m 它将下载数据。
综上所述, 我知道如何设置这个调度程序在我想做的时候做我想做的事。我只是不知道我应该在哪里设置这个抽象应用程序上下文。
您可以创建 f.e。一些 class 用 @Service 注释并将计划的方法放在其中。
@Service
public class SchedulerService {
@Scheduled(cron="0 4 * * * ?")
public void loadDataInDB() {
. . .
}
}
感谢您的回答,但我认为我找到了最好的答案:
public class MyAppServletContextListener
implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
}
//Run this before web application is started
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
AbstractApplicationContext context = new AnnotationConfigApplicationContext(ApplicationScheduler.class);
}
}