преобразовать файл конфигурации application.yml в application.groovy в Grails 3.x

Я пытаюсь создать простой проект Grails 3 и застрял на чем-то очень простом. Поэтому я хочу, чтобы свойства источника данных исходили из параметров виртуальной машины, которые я установил в своей IntelliJ IDE. Раньше в Grails 2.x я просто делал что-то вроде:

environments {
    development{
        //Database connection properties
        def dbserver = System.properties.getProperty('dbserver')
        def dbport = System.properties.getProperty('dbport')
        ............
        dataSource {
            url: "jdbc:sqlserver://${dbserver}:${dbport};databaseName=${dbname}
        } 
    }

Теперь, когда у меня есть application.yml, как мне получить доступ к «System.properties» и встроить его в yml? Я читал, что мы можем вместо этого использовать application.groovy, если YML не поддерживает его, в этом случае это то, как выглядит application.groovy:

grails {
    profile = 'web'
    codegen {
        defaultPackage = 'defPack'
    }
}

info {
    app {
        name = '@info.app.name@'
        version = '@info.app.version@'
        grailsVersion = '@info.app.grailsVersion@'
    }
}

spring {
    groovy {
        template['check-template-location'] = false
    }
}

hibernate {
    naming_strategy = 'org.hibernate.cfg.DefaultNamingStrategy'
    cache {
        queries = false
    }
}

grails {
    mime {
        disable {
            accept {
                header {
                    userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
                }
            }
        }

        types {
            all = '*/*'
            atom = 'application/atom+xml'
            css = 'text/css'
            csv = 'text/csv'
            form = 'application/x-www-form-urlencoded'
            html = ['text/html', 'application/xhtml+xml']
            js = 'text/javascript'
            json = ['application/json', 'text/json']
            multipartForm = 'multipart/form-data'
            rss = 'application/rss+xml'
            text = 'text/plain'
            hal = ['application/hal+json', 'application/hal+xml']
            xml = ['text/xml', 'application/xml']
        }
    }
    urlmapping {
        cache {
            maxsize = 1000
        }
    }
    controllers {
        defaultScope = 'singleton'
    }
    converters {
        encoding = 'UTF-8'
    }
    views {
        default { codec = 'html' }
        gsp {
            encoding = 'UTF-8'
            htmlcodec = 'xml'
            codecs {
                expression = 'html'
                scriptlets = 'html'
                taglib = 'none'
                staticparts = 'none'
            }
        }
    }
}
dataSource {
    pooled = true
    jmxExport = true
    driverClassName = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
    dbCreate = ''
    username = 'someUsername'
    password = 'somePass'
}
environments {
    development {
        dataSource {
            url = 'jdbc:sqlserver://localhost:1234;databaseName=someDbName;'
        }
    }
}

Спасибо.

ОБНОВЛЕНИЕ:

application.groovy не используется по умолчанию, даже когда я удалил application.yml


person Deewendra Shrestha    schedule 05.05.2015    source источник
comment
В последней части вам нужно будет их процитировать: userAgents = ['Gecko', 'WebKit']   -  person Ian Roberts    schedule 05.05.2015
comment
@IanRoberts, спасибо, я обновлю свой пост.   -  person Deewendra Shrestha    schedule 05.05.2015


Ответы (2)


Оказалось, у меня была проблема, мне нужно было поместить ключевое слово «по умолчанию» в кавычки. Нравиться :

grails {
    profile = 'web'
    codegen {
        defaultPackage = 'defPack'
    }
}

info {
    app {
        name = '@info.app.name@'
        version = '@info.app.version@'
        grailsVersion = '@info.app.grailsVersion@'
    }
}

spring {
    groovy {
        template['check-template-location'] = false
    }
}

hibernate {
    naming_strategy = 'org.hibernate.cfg.DefaultNamingStrategy'
    cache {
        queries = false
    }
}

grails {
    mime {
        disable {
            accept {
                header {
                    userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
                }
            }
        }

        types {
            all = '*/*'
            atom = 'application/atom+xml'
            css = 'text/css'
            csv = 'text/csv'
            form = 'application/x-www-form-urlencoded'
            html = ['text/html', 'application/xhtml+xml']
            js = 'text/javascript'
            json = ['application/json', 'text/json']
            multipartForm = 'multipart/form-data'
            rss = 'application/rss+xml'
            text = 'text/plain'
            hal = ['application/hal+json', 'application/hal+xml']
            xml = ['text/xml', 'application/xml']
        }
    }
    urlmapping {
        cache {
            maxsize = 1000
        }
    }
    controllers {
        defaultScope = 'singleton'
    }
    converters {
        encoding = 'UTF-8'
    }
    views {
        'default' { codec = 'html' }//THIS WAS THE SOURCE OF ERROR
        gsp {
            encoding = 'UTF-8'
            htmlcodec = 'xml'
            codecs {
                expression = 'html'
                scriptlets = 'html'
                taglib = 'none'
                staticparts = 'none'
            }
        }
    }
}

def dbserver = System.properties.getProperty('dbserver')
def dbport = System.properties.getProperty('dbport')
def dbusername = System.properties.getProperty('dbusername')
def dbpassword = System.properties.getProperty('dbpassword')
def dbname = System.properties.getProperty('dbname')

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
    dbCreate = ''
    username = dbusername
    password = dbpassword
}
environments {
    development {
        dataSource {
            url = 'jdbc:sqlserver://${dbserver}:${dbport};databaseName=${dbname}'
        }
    }
}
person Deewendra Shrestha    schedule 12.05.2015
comment
как вы добавили файл application.groovy? значит сам сделал..? как в вашем обновлении вы сказали, что он не принимает по умолчанию!! И чем в файле application.groovy возможен доступ к System.properties и другим объектам, связанным с Java/Groovy. К вашему сведению, мне также нужно использовать мои собственные созданные классные объекты класса [Необходимо импортировать классы]. Не могли бы вы указать какое-то решение по этому поводу! - person emphywork; 11.11.2016
comment
Да, вам придется добавить его вручную, а затем избавиться от файла application.yml, иначе я думаю, что приоритет отдается версии yml, а не заводной. Да, в файле groovy вы можете использовать любые System.properties, я не пробовал импортировать классы, но вы можете попробовать импортировать и посмотреть, что произойдет. - person Deewendra Shrestha; 11.11.2016

Может быть не прямой ответ на ваш вопрос. Вы можете получить доступ к системным свойствам в application.yml, добавив ниже в build.gradle

tasks.withType(org.springframework.boot.gradle.run.BootRunTask) {
systemProperties = System.properties

Ссылка: https://github.com/grails/grails-core/issues/9086

person Gandhi    schedule 08.08.2016