gpt4 book ai didi

grails - 在运行时设置数据源值

转载 作者:行者123 更新时间:2023-12-02 14:44:29 25 4
gpt4 key购买 nike

所以从本质上讲,我试图在AppFog上启动并运行我的项目。数据源信息存储在一个环境变量中,该变量本质上是JSON。我的目标是获取此数据并从中设置数据源配置。

这是我尝试过的:

设置数据源配置的代码,这是POGO中的一种方法。实例化POGO,并在DataSource.groovy的开头调用该方法:

import appfog.ParseDataSource
new ParseDataSource().setConfig()

dataSource {
...
}

class ParseDataSource {

void setConfig() {
String env = java.lang.System.getenv("VCAP_SERVICES")
if (env) {
def config = JSON.parse(env)
config = config["mysql-5.1"][0].credentials
grailsApplication.config.environments.production.dataSource.username = config.username
grailsApplication.config.environments.production.dataSource.password = config.password
grailsApplication.config.environments.production.dataSource.url = "jdbc:mysql://" + config.host + ":" + config.port + "/" + config.name
}
}
}

问题是grailsApplication始终为null。我试过在resources.groovy中注册一个Spring bean:
beans = {
parseDataSource(appfog.ParseDataSource) {
grailsApplication = ref('grailsApplication')
}
}

class ParseDataSource {
def grailsAPplication
...
}

我也尝试过通过Holder获取它:
    GrailsApplication grailsApplication = Holders.grailsApplication

无论哪种方式都为null,所以我做的事情不正确。有任何想法吗?

最佳答案

我认为您正在使这一过程变得过于复杂。在仍在构建过程中覆盖grails config对象将导致操作顺序问题,这将使代码非常脆弱。

直接设置值似乎更直接:

Datasource.groovy:

def configJson = JSON.parse(java.lang.System.getenv("VCAP_SERVICES"))
def mysqlConfig = configJson["mysql-5.1"][0].credentials

dataSource = {
production = {
username = mysqlConfig.username
// etc.
}
}

如果为了清晰起见,希望继续在其自己的类中进行解析,请创建values属性并在 dataSource块中读取它们,而不是尝试将它们放入grails config对象中:

配置解析:
class EnvironmentConfigParser {
String username
String password
String url

EnvironmentConfigParser() {
def configJson = JSON.parse(java.lang.System.getenv("VCAP_SERVICES"))
def mysqlConfig = configJson["mysql-5.1"][0].credentials

username = mysqlConfig.username
password = mysqlConfig.password
url = "jdbc:mysql://${mysqlConfig.host}:${mysqlConfig.port}/${mysqlConfig.name}"
}
}

在Datasource.groovy中:
def parser = new EnvironmentConfigParser()

dataSource = {
production = {
username = parser.username
// etc
}
}

关于grails - 在运行时设置数据源值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17912200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com