Spring Groovy配置:导入ConfigSlurper属性

时间:2014-12-06 14:06:35

标签: spring groovy import config

我正在尝试使用Groovy配置我的Spring应用程序。我有几个模块,因此整个上下文被拆分为几个.groovy文件。

我使用suggested method使用外部属性部分)使用ConfigSlurper从外部文件中读取属性,因此在我的主context.groovy中定义了props个对象,使用:

def props = new ConfigSlurper("dev").parse("app.properties")    
beans {
    someBean(SomeBean) {
        commonShinyProperty = props.common.shiny
    }
}

app.properties的位置:

common {
    shiny = true
}

我要做的是在另一个上下文部分props 重用相同的属性源(anotherContext.groovy对象) - 类似于:

importBeans('classpath:context.groovy')
beans {
    anotherBean(AnotherBean) {        
        commonShinyProperty = props.common.shiny
    }
}

此代码不起作用,因为props在此处不可用,只有来自context.groovy的bean。即使它被定义为bean,应用程序也无法以Cannot get property 'shiny' on null objectNo such property: for class...

之类的错误开始

请建议是否可以进行此类配置。提前谢谢!

1 个答案:

答案 0 :(得分:1)

属性文件是通过org.springframework.boot.context.config.ConfigFileApplicationListener加载的,这是在真正加载应用程序上下文之前发生的。

我自定义了GroovyPropertySource以在类路径上加载application.groovy,因此当需要配置时,它将通过相同的Environment.getProperty()提供给应用程序上下文。

查看https://github.com/davidiamyou/spring-groovy-config

您应该可以执行类似

的操作
beans {
    anotherBean(AnotherBean) {        
        commonShinyProperty = '${common.shiny}'
    }
}