springBoot启动时自动执行指定的方法的五种实现方式

小灰灰 2020-11-20 17:59 944阅读 0赞

在springBoot中我们有时候需要让项目在启动时提前加载相应的数据到缓存中或者执行某个方法,那么实现提前加载的方式有哪些呢?接下来我带领大家逐个解答

一、实现ApplicationRunner接口

  1. /** * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个applicationrunner bean * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。 */
  2. @Override
  3. public void run(ApplicationArguments args) throws Exception {
  4. System.out.println("ApplicationRunner的run方法");
  5. }

二、实现CommandLineRunner接口

  1. /** * 用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个commandlinerunner bean,并且可以使用有序接口或@order注释对其进行排序。 * 如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner。 * */
  2. @Override
  3. public void run(String... ) throws Exception {
  4. System.out.println("CommandLineRunner的run方法");
  5. }

三、将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行

  1. @Component
  2. public class Test2 {
  3. //静态代码块会在依赖注入后自动执行,并优先执行
  4. static{
  5. System.out.println("---static--");
  6. }
  7. /** * @Postcontruct’在依赖注入完成后自动调用 */
  8. @PostConstruct
  9. public static void haha(){
  10. System.out.println("@Postcontruct’在依赖注入完成后自动调用");
  11. }
  12. }

四、实现ServletContextListener接口

  1. /** * 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。 */
  2. @Override
  3. public void contextInitialized(ServletContextEvent sce) {
  4. //ServletContext servletContext = sce.getServletContext();
  5. System.out.println("执行contextInitialized方法");
  6. }

五、实现ServletContextAware接口并重写其setServletContext方法

  1. @Component
  2. public class TestStarted implements ServletContextAware {
  3. /** * 在填充普通bean属性之后但在初始化之前调用 * 类似于initializingbean的afterpropertiesset或自定义init方法的回调 * */
  4. @Override
  5. public void setServletContext(ServletContext servletContext) {
  6. System.out.println("setServletContext方法");
  7. }
  8. }

注意:该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行

发表评论

表情:
评论列表 (有 0 条评论,944人围观)

还没有评论,来说两句吧...

相关阅读