我正在尝试使用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 object
或No such property: for class...
请建议是否可以进行此类配置。提前谢谢!
答案 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}'
}
}