java - Spring 在启动时忽略失败

标签 java spring spring-boot startup

当 Spring 应用程序准备就绪时,我需要执行一些工作,类似于 @Scheduled 但我希望它只执行一次。 我找到了一些方法来做到这一点,例如在 bean 上使用 @PostConstruct、使用 @EventListenerInitializingBean,但是,所有这些方法不符合我的需要。如果在执行此逻辑期间出现问题,我想忽略它,以便应用程序无论如何都会启动。但使用这些方法应用程序会崩溃。

当然,我可以用 try-catch 包围逻辑,它会起作用。但是,还有更优雅的方式吗?

最佳答案

我们的微服务也遇到了类似的问题,为了在启动后立即运行代码,我们添加了一个组件。

ApplicationStartup implements ApplicationListener<ApplicationReadyEvent>

在应用程序启动后立即调用服务的应用程序中,这对我们有用。

@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    YourService yourService;

    @Override
    public void onApplicationEvent(final ApplicationReadyEvent event) {

        System.out.println("ApplicationReadyEvent: application is up");
        try {
            // some code to call yourservice with property driven or constant inputs 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


} 

关于java - Spring 在启动时忽略失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59986272/

相关文章:

java - 用于代码操作的 Eclipse 抽象语法树解析器的替代方案

java - 我如何从 Android SDK 解析 PHP 数组?

javascript - 如何定义 Spring WebSocket 订阅者路径

java - Springboot 不会使用 Thymeleaf 加载我的 HTML 页面

Java:Morphia 用新字段值更新集合有多容易

java - 2D 数组 : 1 dimension determined at run time, 其他在编译时已知

java - @ComponentScan 和 @Bean 在上下文配置中有什么区别?

java - Spring 应用程序中的实用程序类 - 我应该使用静态方法吗?

spring-boot - 如何通过Elasticsearch查找排序数据-Spring Boot

java - 无法加载资源: the server responded with a status of 404 (Vaadin 14 + Spring Boot)