如何从命令行重写Grails配置

6
我正在尝试从命令行覆盖dataSource.url值,例如在Grails中运行。
grails <set property> dbm-status

我的第一次尝试是使用-D命令行参数作为

grails -DdataSource.url=jdbc:sqlserver://xx.xx.xx.xx;databaseName=db_name

我尝试添加一个额外的配置文件到 grails.config.locations,从 System.getProperty 获取值,但似乎没有起作用。
是否有内置的方法可以从命令行覆盖配置值?否则我该如何将参数从命令行注入到 Grails 配置中?
编辑:我不想使用另一个环境/数据源来避免重复配置数据源以及为这个新环境进行配置的需要。

你可能需要将其作为单独的数据源添加,如文档所示 - dmahapatro
我正在尝试使用产品数据源启动项目,只替换数据库名称。我需要多次运行迁移脚本,不想复制生产数据源。此外,我的数据源URL已在属性文件中外部化,我们有3个生产环境(prod1、prod2、qa)。 - carlo-colombo
3个回答

2

通过在 DataSource.groovy 中包含以下 if,如果提供了url,则可以覆盖url、密码和用户名属性。(适用于Grails 2.x)

....
environments {
    development {
        dataSource {
        url = "jdbc:postgresql://localhost/db"
        username = "user"
        password = "pass"
        if (System.properties['dataSourceUrl']) {
            println 'Taking dataSource url, password, username from command line overrides'
            url = System.properties['dataSourceUrl']
            password = System.properties['dataSourcePassword']
            username = System.properties['dataSourceUsername']
        }
    }
}
...

现在当我运行命令时,覆盖效果已经生效:
grails dev -DdataSourceUrl=newUrl -DdataSourcePassword=newPass -DdataSourceUsername=newUser run-app

不幸的是,如果您想在每个环境上进行覆盖,您必须为每个环境块复制此代码。如果将其提升到根目录,则无法正常工作,因为配置合并会生效,并且最后一次运行将实际应用 env {} 块中的内容,而不是系统属性中的内容。

再次查看它,类似这样的东西看起来更好:

...
   url = System.properties['dataSourceUrl'] ?: 'jdbc:postgresql://localhost/db'
   //and for every property...
...

0
DATASOURCE_URL=jdbc:sqlserver://xx.xx.xx.xx;databaseName=db_name grials run-app

对于您想要设置的任何变量,您都可以将其设置在环境中。将其转换为大写并用下划线替换点。这是Spring Boot的一个功能。


0

我的情况:

Grails 4.0.3,使用application.yml进行配置。

运行命令:

grails -DdataSourceUrl="jdbc:sqlserver://xx.xx.xx.xx;databaseName=db_name"

更新了build.gradle文件(添加了bootRun任务并加入了这行代码):

// value for this property is being set in task: setDataSourceEnv
systemProperty 'dataSourceUrl', System.getProperty('dataSourceUrl')

生成的任务代码将如下所示:

bootRun {
    ignoreExitValue true
    jvmArgs(
            '-Dspring.output.ansi.enabled=always',
            '-noverify',
            '-XX:TieredStopAtLevel=1',
            '-Xmx2048m')
    sourceResources sourceSets.main
    String springProfilesActive = 'spring.profiles.active'
    systemProperty springProfilesActive, System.getProperty(springProfilesActive)
    // value for this property is being set in task: setDataSourceEnv
    systemProperty 'dataSourceUrl', System.getProperty('dataSourceUrl')
}

已更新 grails-app/conf/application.yml 文件,使用变量 dataSourceUrl(如果您喜欢,也可以使用点号):

environments:
    development:
        dataSource:
            dbCreate: create-drop
            url: "${dataSourceUrl}"

我从这个问题本身这里得到了使用build.gradle的想法。

希望能有所帮助。 编码愉快!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接