在springBoot中我们有时候需要让项目在启动时提前加载相应的数据或者执行某个定时任务,那么实现启动时自动运行自定义方法的方式有哪些呢?
1. 实现 CommandLineRunner 接口
@Component
public class TestStart implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("实现 CommandLineRunner 接口");
}
}
用于指示Bean包含在SpringApplication中时应运行的接口。
可以在同一应用程序上下文中定义多个CommandLineRunner Bean,并且可以使用有序接口或@order注释对其进行排序
2. 实现 ApplicationRunner 接口
@Component
public class TestStart implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("实现 ApplicationRunner 接口");
}
}
用于指示bean包含在SpringApplication中时应运行的接口。
可以定义多个ApplicationRunner Bean
3. 实现 ServletContextAware 接口
@Component
public class TestStart implements ServletContextAware {
@Override
public void setServletContext(ServletContext servletContext) {
System.out.println("实现 ServletContextAware 接口");
}
}
该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行。
4. 实现 ServletContextListener 接口
@Component
public class TestStart implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("实现 ServletContextListener 接口");
}
}
在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。
5. @Component + @PostConstruct
@Component
public class TestStart {
@PostConstruct
public static void test() {
System.out.println("@Component + @PostConstruct");
}
}