【springBoot】项目启动时验证数据库


当数据库连接失败时拒绝启动项目

 1 import org.springframework.beans.BeansException;
 2 import org.springframework.context.ApplicationContext;
 3 import org.springframework.context.ApplicationContextAware;
 4 import org.springframework.stereotype.Component;
 5 
 6 import javax.sql.DataSource;
 7 
 8 @Component
 9 public class ApplicationContextHelper implements ApplicationContextAware {
10 
11     private static ApplicationContext context;
12 
13     @Override
14     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
15         try {
16             context = applicationContext;
17             // ===== 在项目初始化bean后检验数据库连接是否
18             DataSource dataSource = (DataSource) context.getBean("dataSource");
19             dataSource.getConnection().close();
20         } catch (Exception e) {
21             e.printStackTrace();
22             // ===== 当检测数据库连接失败时, 停止项目启动
23             System.exit(-1);
24         }
25     }
26 
27     public ApplicationContext getApplicationContext() {
28         return context;
29     }
30 
31 }

摘自:https://blog.csdn.net/qq_16736531/article/details/102522838


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM