关于java:Spring-Boot-启动时让方法自动执行的-4-种方法

5次阅读

共计 1727 个字符,预计需要花费 5 分钟才能阅读完成。

作者:FOEVERYANG

起源:https://www.cnblogs.com/lsgsp…

在 springBoot 中咱们有时候须要让我的项目在启动时提前加载相应的数据或者执行某个办法,那么实现提前加载的形式有哪些呢?

接下来我率领大家一一解答

1、实现 ServletContextAware 接口并重写其 setServletContext 办法

@Component
public class TestStarted implements ServletContextAware {
    /**
     * 在填充一般 bean 属性之后但在初始化之前调用
     * 相似于 initializingbean 的 afterpropertiesset 或自定义 init 办法的回调
     *
     */
    @Override
    public void setServletContext(ServletContext servletContext) {System.out.println("setServletContext 办法");
    }
}

留神:该办法会在填充完一般 Bean 的属性,然而还没有进行 Bean 的初始化之前执行

2、实现 ServletContextListener 接口

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

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

@Component
public class Test2 {
    // 动态代码块会在依赖注入后主动执行, 并优先执行
    static{System.out.println("---static--");
    }
    /**
     *  @Postcontruct’在依赖注入实现后主动调用
     */
    @PostConstruct
    public static void haha(){System.out.println("@Postcontruct’在依赖注入实现后主动调用");
    }
}

4、实现 ApplicationRunner 接口

/**
 * 用于批示 bean 蕴含在 SpringApplication 中时应运行的接口。能够定义多个 applicationrunner bean
 * 在同一应用程序上下文中,能够应用有序接口或 @order 正文对其进行排序。*/
@Override
public void run(ApplicationArguments args) throws Exception {System.out.println("ApplicationRunner 的 run 办法");
}

5、实现 CommandLineRunner 接口

/**
 * 用于批示 bean 蕴含在 SpringApplication 中时应运行的接口。能够在同一应用程序上下文中定义多个 commandlinerunner bean,并且能够应用有序接口或 @order 正文对其进行排序。* 如果须要拜访 applicationArguments 而不是原始字符串数组,请思考应用 applicationrunner。* 
 */
@Override
public void run(String...) throws Exception {System.out.println("CommandLineRunner 的 run 办法");
}

学习了,你晓得几种?

近期热文举荐:

1.600+ 道 Java 面试题及答案整顿 (2021 最新版)

2. 终于靠开源我的项目弄到 IntelliJ IDEA 激活码了,真香!

3. 阿里 Mock 工具正式开源,干掉市面上所有 Mock 工具!

4.Spring Cloud 2020.0.0 正式公布,全新颠覆性版本!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

正文完
 0