本篇内容主要讲解“java使用springboot-starter启动检查配置是否满足要求”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java使用springboot-starter启动检查配置是否满足要求”吧!
主要有以下几个检测项:
1. 环境变量的检查
2. java运行变量的检查
3. 指定位置文件的检查
4. host检查
要想一启动程序就运行,我们自然而然就想到了springboot 的 starter 项目,对,我们把这个也封装成一个starter, 这样一启动springboot应用,就可以检查各种条件了.
引入依赖:
dependencies { implementation platform('org.springframework.boot:spring-boot-dependencies:2.1.6.RELEASE') compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure' }
项目结构如下图所示
spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.platform.tools.starter.spring.boot.ToolAutoConfigurationorg.springframework.context.ApplicationContextInitializer=\com.platform.tools.starter.spring.boot.ToolApplicationContextInitializer
ToolAutoConfiguration.java
@Configurationpublic class ToolAutoConfiguration {}
ToolApplicationContextInitializer.java
public class ToolApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("write check code here"); }}
运行效果如下:
这样我们就做到了在项目一启动的时候就运行检测代码的效果
如上所述有环境变量,文件等简单的校验,本文以apollo的检测为例写几个典型的获取配置的代码,下面的代码中包含判断文件是否存在,判断环境变量,判断系统变量
public class InitCheck { /** 操作系统类别: 1是win, 2是其他 */ private Integer osType; /** 环境变量的map */ private Map<String ,String> envMap = System.getenv(); public InitCheck() { //获取操作系统类型 String osName = System.getProperty("os.name"); this.osType = osName.contains("windows")?1:2; } /** * 对外提供的调用方法,在 new 完InitCheck之后,就调用这个方法 * * @return */ public boolean checkAll(){ return checkApollo(); } /** * 检查apollo的配置是否正确 * @return */ private boolean checkApollo(){ //apollo主要是检查ENV有没有设置,而且只检查环境变量和文件 String env = envMap.get("ENV"); boolean envFlag = env != null && !env.isEmpty(); String filePath = osType==1?"C:/opt/settings/server.properties":"/opt/settings/server.properties"; boolean fileFlag = Files.exists(Paths.get(filePath)); boolean result = envFlag || fileFlag; if(!result){ System.out.printf("请正确配置apollo , 设置环境变量 ENV=dev 或者在文件 %s 中写入 ENV=dev \n",filePath); } return result; }}
运行效果如下图所示:
其他检查代码因不好脱敏,就先不发出来了,但思路都是一致的,大家也可以写一写尝试下
到此,相信大家对“java使用springboot-starter启动检查配置是否满足要求”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/3221172/blog/4377226