SpringBoot 启动时立即让方法自动执行的四种方法

淩亂°似流年 2022-11-06 11:57 367阅读 0赞

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

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

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

2、实现ServletContextListener接口

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

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

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

4、实现ApplicationRunner接口

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

5、实现CommandLineRunner接口

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

发表评论

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

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

相关阅读