千家信息网

java使用springboot-starter启动检查配置是否满足要求

发表于:2025-12-01 作者:千家信息网编辑
千家信息网最后更新 2025年12月01日,本篇内容主要讲解"java使用springboot-starter启动检查配置是否满足要求",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"java使用spr
千家信息网最后更新 2025年12月01日java使用springboot-starter启动检查配置是否满足要求

本篇内容主要讲解"java使用springboot-starter启动检查配置是否满足要求",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"java使用springboot-starter启动检查配置是否满足要求"吧!

检查配置

主要有以下几个检测项:
1. 环境变量的检查
2. java运行变量的检查
3. 指定位置文件的检查
4. host检查

运行启动

要想一启动程序就运行,我们自然而然就想到了springboot 的 starter 项目,对,我们把这个也封装成一个starter, 这样一启动springboot应用,就可以检查各种条件了.

制作starter

引入依赖:

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 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启动检查配置是否满足要求"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0