【问题标题】:Executing some method in class after starting application spring-boot启动应用程序spring-boot后在类中执行某些方法
【发布时间】:2017-12-18 11:24:31
【问题描述】:

我有一个spring-boot 服务器应用程序。在其中一个函数中,我运行了一些预定的线程:

 private  ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
    private threadsNumber = 10;

    @PostConstruct
    void startThreads() {
          for (int i = 1; i <= threadsNumber; ++i){
                pool.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                            //set Thread Local in depends on i
                            // do some other stuff

                        }
                    }
                }, 0, 10, TimeUnit.SECONDS);
            }
        }
    }
}

问题是:
如何在spring-boot中避免注释@PostConstruct并得到结果:“启动应用程序后只执行一次”

【问题讨论】:

  • 在构造函数中执行你的代码。 spring 将启动 bean,您可以执行调度程序

标签: java spring spring-boot threadpool


【解决方案1】:

Spring 提供了ApplicationListener&lt;ContextRefreshedEvent&gt; 接口及其onApplicationEvent(ContextRefreshedEvent event) 钩子。

例如:

public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
      // do something on container startup
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2019-09-16
    • 2017-10-09
    • 2015-05-10
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多