SpringBoot项目启动时自动运行自定义方法
在SpringBoot项目中有时候我们需要项目在启动时提前加载某些数据或执行某个方法,如:
- 开启Quartz定时任务调度器;
- 初始化sql,创建数据库。
方法一:实现ServletContextAware接口并重写其setServletContext方法,将其注入到Spring容器中
1 |
|
使用该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行自定义方法。
方法二:实现ServletContextListener接口并重写其contextInitialized方法,将其注入到Spring容器中
1 |
|
方法三:将要执行的方法所在的类交给Spring容器扫描(@Component),并且将要执行的方法放入静态代码块中
1 |
|
方法四:将要执行的方法所在的类交给spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解
1 |
|
方法五:实现ApplicationRunner接口并重写其run方法,将其注入到Spring容器中
1 |
|
方法六:实现CommandLineRunner接口并重写其run方法,将其注入到Spring容器中
1 |
|
以上六种方法在SpringBoot项目启动时的执行顺序
1 | 2021-07-05 16:48:56.973 [main] [INFO] [org.apache.juli.logging.DirectJDKLog:180] - Starting Servlet Engine: Apache Tomcat/8.5.43 |