【问题标题】:How to pass database name explicitly in application.properties file not through the datasource.URL如何不通过 datasource.URL 在 application.properties 文件中显式传递数据库名称
【发布时间】:2020-12-15 11:57:27
【问题描述】:

如何显式传递数据库名称 application.properties 文件不通过 datasource.URL

spring.datasource.url = jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username = root
spring.datasource.password = root

【问题讨论】:

    标签: java spring spring-boot jdbc


    【解决方案1】:

    您可以使用额外的属性并在数据源 URL 中使用它,例如 ${your-propname}

    结果:

    database-name=mydatabase
    
    spring.datasource.url = jdbc:mysql://localhost:3306/${database-name}
    spring.datasource.username = root
    spring.datasource.password = root
    

    如果您想通过系统属性传递数据库名称,您可以使用

    database-name=${database:mydatabase}
    spring.datasource.url = jdbc:mysql://localhost:3306/${database-name}
    

    在这里你可以通过java -Ddatabase=xxx传递属性... 如果启动时缺少此属性,则在 : 之后使用默认值(例如 => mydatabase)

    注意:你应该看看config-files-profile-specific

    【讨论】:

    • 我们也可以在迁移脚本中以${your-propname} 的方式使用数据库吗?
    • 改进了我的答案,希望对您有所帮助
    • 不确定您的意思:迁移脚本中的用法
    猜你喜欢
    • 2018-11-13
    • 2023-01-02
    • 2021-03-11
    • 2011-08-21
    • 2014-11-06
    • 2012-10-07
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    相关资源
    最近更新 更多