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

如何不借助Spring仅用Java运行Liquibase迁移并读取liquibase.properties配置

纯Java环境读取liquibase.properties运行Liquibase的实现方案

第一步:准备配置文件

在项目resources根目录下新建liquibase.properties,常用配置参考如下:

# 数据库连接配置
driver: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8
username: root
password: your_password
# changelog配置
changeLogFile: db/changelog/master.xml
# 可选配置:上下文、执行标签
contexts: dev
labels: init

第二步:编写执行代码

直接通过JDK原生的Properties类加载配置文件,解析参数后初始化Liquibase实例即可,无需依赖额外框架:

import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.resource.ClassLoaderResourceAccessor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class LiquibaseStarter {
    public static void main(String[] args) {
        Properties liquibaseProps = new Properties();
        try {
            // 读取类路径下的liquibase.properties
            liquibaseProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("liquibase.properties"));
            
            // 解析数据库连接参数,创建JDBC连接
            String driver = liquibaseProps.getProperty("driver");
            String jdbcUrl = liquibaseProps.getProperty("url");
            String username = liquibaseProps.getProperty("username");
            String password = liquibaseProps.getProperty("password");
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
            
            // 初始化Liquibase
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            String changeLogPath = liquibaseProps.getProperty("changeLogFile");
            Liquibase liquibase = new Liquibase(changeLogPath, new ClassLoaderResourceAccessor(), database);
            
            // 读取上下文和标签参数执行更新,无配置则传空值
            String contexts = liquibaseProps.getProperty("contexts", "");
            String labels = liquibaseProps.getProperty("labels", "");
            liquibase.update(contexts, labels);
            
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

前置依赖确认

确保项目中已经引入liquibase-core依赖,Maven配置参考:

<dependency>
    <groupId>org.liquibase</groupId>
    <artifactId>liquibase-core</artifactId>
    <version>4.20.0</version> <!-- 可替换为对应业务兼容的版本 -->
</dependency>

注意事项

  • 配置文件中的changeLogFile路径为相对于resources目录的相对路径,ClassLoaderResourceAccessor会自动从类路径下查找对应文件
  • 如需执行回滚、校验等其他操作,替换liquibase.update()为对应rollback、validate等方法即可,参数逻辑一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:09:04