看看https://gist.github.com/reduardo7/d14ea1cd09108425e0f5ecc8d3d7fca0
Grails 3 中的外部配置
在Grails 3上工作我意识到我不能再使用Config.groovy 文件中的标准grails.config.locations 属性来指定外部配置。
原因很明显! Grails 3 中现在没有Config.groovy。相反,我们现在使用application.yml 来配置属性。但是,您也不能使用此文件指定外部配置!
什么破解?
现在 Grails 3 使用 Spring 的属性源概念。为了使外部配置文件能够工作,我们现在需要做一些额外的事情。
假设我想用我的外部配置文件覆盖application.yml 文件中的一些属性。
例如,从这个:
dataSource:
username: sa
password:
driverClassName: "org.h2.Driver"
到这里:
dataSource:
username: root
password: mysql
driverClassName: "com.mysql.jdbc.Driver"
首先我需要将此文件放在应用程序的根目录中。例如,我使用外部配置文件 app-config.yml 遵循 Grails 3 应用程序的结构:
[human@machine tmp]$ tree -L 1 myapp
myapp
├── app-config.yml // <---- external configuration file!
├── build.gradle
├── gradle
├── gradle.properties
├── gradlew
├── gradlew.bat
├── grails-app
└── src
现在,要启用读取此文件,只需添加以下内容:
到您的build.gradle 文件
bootRun {
// local.config.location is just a random name. You can use yours.
jvmArgs = ['-Dlocal.config.location=app-config.yml']
}
到您的Application.groovy 文件
package com.mycompany
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean
import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.core.env.PropertiesPropertySource
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.Resource
class Application extends GrailsAutoConfiguration implements EnvironmentAware {
public final static String LOCAL_CONFIG_LOCATION = "local.config.location"
static void main(String[] args) {
GrailsApp.run(Application, args)
}
@Override
void setEnvironment(Environment environment) {
String configPath = System.properties[LOCAL_CONFIG_LOCATION]
if (!configPath) {
throw new RuntimeException("Local configuration location variable is required: " + LOCAL_CONFIG_LOCATION)
}
File configFile = new File(configPath)
if (!configFile.exists()) {
throw new RuntimeException("Configuration file is required: " + configPath)
}
Resource resourceConfig = new FileSystemResource(configPath)
YamlPropertiesFactoryBean ypfb = new YamlPropertiesFactoryBean()
ypfb.setResources([resourceConfig] as Resource[])
ypfb.afterPropertiesSet()
Properties properties = ypfb.getObject()
environment.propertySources.addFirst(new PropertiesPropertySource(LOCAL_CONFIG_LOCATION, properties))
}
}
注意Application 类实现了EnvironmentAware 接口并覆盖了它的setEnvironment(Environment environment):void 方法。
现在这就是在 Grails 3 应用程序中重新启用外部配置文件所需的全部内容。
代码和指南摘自以下链接,稍作修改:
- http://grails.1312388.n4.nabble.com/Grails-3-External-config-td4658823.html
- https://groups.google.com/forum/#!topic/grails-dev-discuss/_5VtFz4SpDY
来源:https://gist.github.com/ManvendraSK/8b166b47514ca817d36e