如何在Spring中非阻塞地运行@PostConstruct?

mem*_*und 7 java spring spring-boot spring-async

@PostConstruct
public void performStateChecks() {
   throw new RuntimeException("test");
}
Run Code Online (Sandbox Code Playgroud)

如果我spring使用上面的代码启动应用程序,它将阻止该应用程序启动。

我正在寻找的是在启动后直接执行一个方法,但是异步的。意味着,它不应该延迟启动,并且即使发生故障也不应该阻止应用程序运行。

如何使初始化异步?

Nic*_*nia 11

您可以使用EventListener代替PostConstruct,它支持@Async

@Service
public class MyService {    
    @Async
    @EventListener(ApplicationStartedEvent.class)
    public void performStateChecks() {
        throw new RuntimeException("test");
    }
 }
Run Code Online (Sandbox Code Playgroud)

不要忘记通过@EnableAsync注释启用异步支持

您还可以使用其他一些事件,请参阅SpringApplicationEvent类的继承者


Pan*_*kos 0

您可以从方法中删除 @PostConstruct 并让该方法成为普通方法。然后,您可以在 ApplicatioinContext 已加载且应用程序已启动时手动调用它。

 @SpringBootApplication
 public class ServiceLauncher {

 public static void main(String[] args) {

   ConfigurableApplicationContext context = new SpringApplication(ServiceLauncher.class).run(args);

    try {
        context.getBean(YourBean.class).performStateChecks(); // <-- this will run only after context initialization finishes
        } catch (Exception e) {
        //catch any exception here so it does not go down
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)