You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JDK 8环境下非Spring Java应用数据库配置变量外部化方案咨询

无Spring依赖的JDK 8数据库配置外部化方案

嘿,既然你不想用环境变量也不想依赖Spring,那我给你几个纯JDK 8就能搞定的外部化配置方案,都是轻量又好维护的:

1. 使用属性文件(.properties)

这是最常用的纯JDK方案,配置文件直观易修改,不需要额外依赖。

步骤1:创建配置文件

在项目资源目录(比如src/main/resources)下新建db-config.properties,内容如下:

dbHost=localhost
dbPort=8091
bucketName=demo_bucket

步骤2:编写配置加载类

用JDK自带的Properties类加载配置,结合try-with-resources确保资源安全关闭:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class DbConfig {
    private static final Properties CONFIG = new Properties();

    // 静态代码块初始化配置,程序启动时加载一次
    static {
        try (InputStream input = DbConfig.class.getClassLoader().getResourceAsStream("db-config.properties")) {
            if (input == null) {
                throw new RuntimeException("找不到配置文件 db-config.properties");
            }
            CONFIG.load(input);
        } catch (IOException e) {
            throw new RuntimeException("加载数据库配置失败", e);
        }
    }

    // 获取配置的方法,添加默认值兜底和类型校验
    public static String getDbHost() {
        return CONFIG.getProperty("dbHost", "localhost");
    }

    public static int getDbPort() {
        String portStr = CONFIG.getProperty("dbPort", "8091");
        try {
            return Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            throw new RuntimeException("dbPort 不是有效的数字格式", e);
        }
    }

    public static String getBucketName() {
        return CONFIG.getProperty("bucketName", "demo_bucket");
    }
}

使用方式

在需要数据库连接的地方直接调用静态方法即可:

String host = DbConfig.getDbHost();
int port = DbConfig.getDbPort();
String bucket = DbConfig.getBucketName();
// 后续用这些参数初始化数据库连接

2. 使用命令行启动参数

如果需要在启动时动态调整配置,这个方案很合适,同样纯JDK原生支持。

启动方式

启动Java程序时通过-D参数传递配置:

java -DdbHost=localhost -DdbPort=8091 -DbucketName=demo_bucket com.yourpackage.YourMainClass

编写配置获取类

用System.getProperty()读取参数,同样可以设置默认值避免启动失败:

public class DbConfig {
    public static String getDbHost() {
        return System.getProperty("dbHost", "localhost");
    }

    public static int getDbPort() {
        String portStr = System.getProperty("dbPort", "8091");
        try {
            return Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            throw new RuntimeException("dbPort 参数格式错误", e);
        }
    }

    public static String getBucketName() {
        return System.getProperty("bucketName", "demo_bucket");
    }
}

3. 可选:使用JSON配置文件(需轻量第三方库)

如果你更习惯JSON格式,可以用Gson或Jackson这类轻量库解析,不需要Spring。这里以Gson为例(JDK 8兼容版本):

步骤1:添加Gson依赖(Maven为例)

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

步骤2:创建JSON配置文件

db-config.json:

{
    "dbHost": "localhost",
    "dbPort": 8091,
    "bucketName": "demo_bucket"
}

步骤3:编写加载类

import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class DbConfig {
    private static final DbConfig INSTANCE;

    static {
        Gson gson = new Gson();
        try (Reader reader = new InputStreamReader(DbConfig.class.getClassLoader().getResourceAsStream("db-config.json"))) {
            INSTANCE = gson.fromJson(reader, DbConfig.class);
        } catch (IOException e) {
            throw new RuntimeException("加载JSON配置失败", e);
        }
    }

    private String dbHost;
    private int dbPort;
    private String bucketName;

    // 私有构造,避免外部实例化
    private DbConfig() {}

    // 获取配置的静态方法
    public static String getDbHost() {
        return INSTANCE.dbHost;
    }

    public static int getDbPort() {
        return INSTANCE.dbPort;
    }

    public static String getBucketName() {
        return INSTANCE.bucketName;
    }
}

方案选择建议

  • 若需要固定配置、方便日常修改,优先选属性文件方案;
  • 若需要在启动时灵活调整参数(比如不同环境切换),选命令行参数方案;
  • JSON方案适合习惯JSON格式的场景,但需要引入一个轻量第三方库。

内容的提问来源于stack exchange,提问作者SST

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:29:24