系列文章目录
文章目录
- 系列文章目录
- 前言
前言
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。
在springBoot中我们有时候需要让项目在启动时提前加载相应的数据或者执行某个方法,具体可以有如下几种方式
1.实现ServletContextAware接口并重写其setServletContext方法
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;import javax.servlet.ServletContext;@Component
public class DemoServletContextAware implements ServletContextAware {// 该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行@Overridepublic void setServletContext(ServletContext servletContext) {System.out.println("------------>>>>>>>>>> ServletContextAware");}2.实现ServletContextListener接口}
2.实现ServletContextListener接口
import org.springframework.stereotype.Component;import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;@Component
public class DemoServletContextListener implements ServletContextListener {// 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("------------>>>>>>>>>> ServletContextListener");}
}
3.将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;@Component
public class DemoClass {// 静态代码块会在依赖注入后自动执行,并优先执行static {System.out.println("------------>>>>>>>>>> static");}// 在依赖注入完成后自动调用@PostConstructpublic static void demo() {System.out.println("------------>>>>>>>>>> PostConstruct");}
}
4.实现ApplicationRunner接口
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(-1)
@Component
public class DemoApplicationRunner implements ApplicationRunner {// 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个applicationrunner bean// 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序@Overridepublic void run(ApplicationArguments args) throws Exception {System.out.println("------------>>>>>>>>>> ApplicationRunner");}
}
4.实现CommandLineRunner接口
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;@Component
public class DemoCommandLineRunner implements CommandLineRunner {// 用于指示bean包含在SpringApplication中时应运行的接口,可以在同一应用程序上下文中定义多个commandlinerunner bean// 可以使用有序接口或@order注释对其进行排序,如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner@Overridepublic void run(String... args) throws Exception {System.out.println("------------>>>>>>>>>> CommandLineRunner");}
}
同时在项目中定义如上代码,执行打印结果为
// 内容省略
------------>>>>>>>>>> ServletContextListener
------------>>>>>>>>>> static
------------>>>>>>>>>> PostConstruct
------------>>>>>>>>>> ServletContextAware
// 中间内容省略
------------>>>>>>>>>> ApplicationRunner
------------>>>>>>>>>> CommandLineRunner