Spring Boot启动时,如何让方法自动运行呢?

戚薇 SpringBoot 发布时间:2023-06-09 22:15:40 阅读数:15280 1
下文笔者讲述SpringBoot启动时,让方法自动运行的示例分享,如下所示

SpringBoot让方法自动的实现思路

方法自动运行的方法
  1.实现ServletContextAware接口并重写其setServletContext方法
  2.实现ServletContextlistener接口
  3.将要执行的方法所在的类交个spring容器扫描(@Component),
      且在要执行的方法上添加@PostConstruct注解或者静态代码块运行
  4.实现ApplicationRunner接口
  5.实现commandlinerunner接口

1.实现ServletContextAware接口并重写其setServletContext方法

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

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 test(){
        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方法");
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202306/6761.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者