如何中止Spring-Boot启动?

Zhu*_*ehi 7 java watchservice spring-boot

我正在编写一个Spring-Boot应用程序来监视目录并处理正在添加到它的文件.我在配置类中使用WatchService注册目录:

@Configuration
public class WatchServiceConfig {

    private static final Logger logger = LogManager.getLogger(WatchServiceConfig.class);

    @Value("${dirPath}")
    private String dirPath;

    @Bean
    public WatchService register() {
        WatchService watchService = null;

        try {
            watchService = FileSystems.getDefault().newWatchService();
            Paths.get(dirPath).register(watchService, ENTRY_CREATE);
            logger.info("Started watching \"{}\" directory ", dlsDirPath);
        } catch (IOException e) {
            logger.error("Failed to create WatchService for directory \"" + dirPath + "\"", e);
        }

        return watchService;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果注册目录失败,我想优雅地中止Spring Boot启动.有人知道我怎么做吗?

Kyl*_*son 10

获取应用程序上下文,例如:

@Autowired
private ConfigurableApplicationContext ctx;
Run Code Online (Sandbox Code Playgroud)

close如果找不到目录,则调用该方法:

ctx.close();
Run Code Online (Sandbox Code Playgroud)

这会优雅地关闭应用程序上下文,从而关闭 Spring Boot 应用程序本身。

更新

基于问题中提供的代码的更详细示例。

主类

@SpringBootApplication
public class GracefulShutdownApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(GracefulShutdownApplication.class, args);
        try{
            ctx.getBean("watchService");
        }catch(NoSuchBeanDefinitionException e){
            System.out.println("No folder to watch...Shutting Down");
            ctx.close();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

手表服务配置

@Configuration
public class WatchServiceConfig {

    @Value("${dirPath}")
    private String dirPath;

    @Conditional(FolderCondition.class)
    @Bean
    public WatchService watchService() throws IOException {
        WatchService watchService = null;
        watchService = FileSystems.getDefault().newWatchService();
        Paths.get(dirPath).register(watchService, ENTRY_CREATE);
        System.out.println("Started watching directory");
        return watchService;
    }
Run Code Online (Sandbox Code Playgroud)

文件夹条件

public class FolderCondition implements Condition{

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String folderPath = conditionContext.getEnvironment().getProperty("dirPath");
        File folder = new File(folderPath);
        return folder.exists();
    }
}
Run Code Online (Sandbox Code Playgroud)

@Conditional根据目录是否存在制作 WatchService Bean 。然后在您的主类中,检查 WatchService Bean 是否存在,如果不存在,则通过调用close().


Abh*_*kar 7

接受的答案是正确的,但不必要的复杂。不需要 a Condition,然后检查 bean 是否存在,然后关闭ApplicationContext。在创建过程中简单地检查目录是否存在WatchService,并抛出异常将由于创建 bean 失败而中止应用程序启动。