java - 启动应用程序 spring-boot 后执行类中的某些方法

标签 java spring spring-boot threadpool

我有一个 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提供了ApplicationListener<ContextRefreshedEvent>接口(interface)及其onApplicationEvent(ContextRefreshedEvent event)钩。

例如:

public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {

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

关于java - 启动应用程序 spring-boot 后执行类中的某些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084679/

相关文章:

java - 状态 403 来自 Postman 的 Post 请求中的 CSRF token 无效

java - 如何将 HttpServletResponse 响应获取到 Spring Boot 的 REST Controller 中?

java - StreamCorruptedException 与 ObjectInputStream 和 ByteArrayInputStream

java - akka camel 将案例类作为消息发送

java - 即时刷新数据库配置

java - 如何在 IntelliJ IDEA 中为 Spring Boot 项目构建 jar Artifact

java - 当我有很多 SpringBootTest 类时,如何有效地使用嵌套配置类来注入(inject)依赖项

java - 除以 0 的正则表达式

java - 无论输入是什么,操作的输出始终为零

java - 带有 Spring Webflow : ClassNotFoundException: org. springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean 的 Maven 项目