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;
}
}
디렉터리 등록에 실패하면 Spring Boot 시작을 정상적으로 중단하고 싶습니다.내가 이걸 어떻게 하는지 아는 사람?
애플리케이션 컨텍스트 가져오기(예:
@Autowired
private ConfigurableApplicationContext ctx;
그럼 전화해봐요close
디렉터리를 찾을 수 없는 경우 메소드:
ctx.close();
그러면 응용 프로그램 컨텍스트가 정상적으로 종료되므로 스프링 부트 응용 프로그램 자체가 종료됩니다.
업데이트:
질문에 제공된 코드를 기반으로 한 보다 자세한 예제입니다.
메인 클래스
@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();
}
}
}
Watch 서비스 구성
@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;
}
폴더 조건
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();
}
}
워치 서비스 빈 만들기@Conditional
디렉터리가 있는지 여부를 기준으로 합니다.그런 다음 메인 클래스에 WatchServiceBean이 있는지 확인하고 없으면 호출하여 응용 프로그램 컨텍스트를 종료합니다.close()
.
받아들여진 답은 맞지만, 불필요하게 복잡합니다.그럴 필요 없어요.Condition
그리고 나서 콩의 존재를 확인하고, 그리고 나서 콩을 닫습니다.ApplicationContext
다음 시간 동안 디렉토리가 있는지 확인하는 것뿐입니다.WatchService
예외를 생성하면 빈 생성 실패로 인해 응용 프로그램 시작이 중단됩니다.
현재 메시지에 문제가 없는 경우IOException
시작을 중단하기 위해 콩을 던지게 할 수 있습니다.
@Bean
public WatchService watchService() throws IOException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(dirPath).register(watchService, ENTRY_CREATE);
logger.info("Started watching \"{}\" directory ", dlsDirPath);
}
기본값보다 친숙한 오류 메시지를 원하는 경우IOException
(사용자가 오류를 더 잘 지적할 수 있도록 돕기 위해) 사용자 정의된 예외 메시지와 함께 자신의 예외를 던질 수 있습니다.
@Bean
public WatchService watchService() {
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(dirPath).register(watchService, ENTRY_CREATE);
logger.info("Started watching \"{}\" directory ", dlsDirPath);
return watchService;
} catch (IOException e) {
throw new IllegalStateException(
"Failed to create WatchService for directory \"" + dirPath + "\"", e);
}
}
각 SpringApplication은 종료 시 ApplicationContext가 정상적으로 닫히도록 JVM에 종료 후크를 등록합니다.모든 표준 Spring 라이프사이클 콜백(예: 일회용 Bean 인터페이스 또는 @PreDestroy 주석)을 사용할 수 있습니다.
또한 콩은 org.springframework.boot를 구현할 수 있습니다.응용 프로그램이 종료될 때 특정 종료 코드를 반환하려면 CodeGenerator 인터페이스를 종료합니다.
리소스/파일을 릴리스하는 @PreDestroy 메서드를 구현해야 합니다.그런 다음 시작하는 동안 오류를 감지하면 몇 개를 던질 수 있습니다.RuntimeException
응용프로그램 컨텍스트를 닫기 시작합니다.
언급URL : https://stackoverflow.com/questions/40940694/how-can-i-abort-spring-boot-startup
'source' 카테고리의 다른 글
입력 크기 대 폭 (0) | 2023.08.07 |
---|---|
Java Spring Boot Project의 저장 프로시저가 null을 출력으로 반환합니다. (0) | 2023.08.07 |
Oracle TO_DATE NOT throw 오류 (0) | 2023.08.02 |
Mac OS X에서 Android SDK를 설치하는 위치는 무엇입니까? (0) | 2023.08.02 |
파이썬에서 스레드 내부에서 호출할 때 sys.exit()이 종료되지 않는 이유는 무엇입니까? (0) | 2023.08.02 |