关于chrome:SpringBoot-启动过程执行某函数

3次阅读

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

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 接口

/**java 我的项目 www fhadmin org

  • 在初始化 Web 应用程序中的任何过滤器或 servlet 之前,将告诉所有 servletContextListener 上下文初始化。
    */

@Override
public void contextInitialized(ServletContextEvent sce) {

//ServletContext servletContext = sce.getServletContext();
System.out.println("执行 contextInitialized 办法");

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

//java 我的项目 www fhadmin org
@Component
public class Test2 {

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

4、实现 ApplicationRunner 接口

/**java 我的项目 www fhadmin org

  • 用于批示 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。
  • java 我的项目
    */

@Override
public void run(String…) throws Exception {

System.out.println("CommandLineRunner 的 run 办法");

}

正文完
 0