How to use external .groovy config file in Grails 3

限于喜欢 提交于 2019-12-05 08:15:59

I found this thread and quotation by Graeme Rocher:

Grails 3 uses Spring's property sources concept, so it will resolve properties from the system, the environment and finally the application.yml/application.groovy

and code by Clyde Balneaves:

class Application extends GrailsAutoConfiguration implements EnvironmentAware {
    static void main(String[] args) {
    GrailsApp.run(Application)
    }

    @Override
    void setEnvironment(Environment environment) {
    //Set up Configuration directory
    def krakenHome = System.getenv('KRAKEN_HOME') ?: System.getProperty('KRAKEN_HOME') ?: "/opt/kraken"

    println ""
    println "Loading configuration from ${krakenHome}"
    def appConfigured = new File(krakenHome, 'KrakenConfig.groovy').exists()
    println "Loading configuration file ${new File(krakenHome, 'KrakenConfig.groovy')}"
    println "Config file found : " + appConfigured

    if (appConfigured) {
        def config = new ConfigSlurper().parse(new File(krakenHome, 'KrakenConfig.groovy').toURL())
        environment.propertySources.addFirst(new MapPropertySource("KrakenConfig", config))
    }
    }
}

May be you can also try this way (Overriding run method)

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import grails.util.Environment
import grails.util.Holders
import org.springframework.boot.CommandLineRunner

class Application extends GrailsAutoConfiguration implements CommandLineRunner {

    static void main(String[] args) {
        GrailsApp.run(Application, args)
    }

    @Override
    void run(final String... args) throws Exception {
        println "Running in ${Environment.current.name}"

        // Get configuration from Holders.
        def config = Holders.getConfig()
        def locations = config.grails.config.locations
        locations.each {
            String configFileName = it.split("file:")[1]
            File configFile = new File(configFileName)
            if (configFile.exists()) {
                config.merge(new ConfigSlurper(Environment.current.name).parse(configFile.text))
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!