简体   繁体   English

Spring Groovy Config:导入ConfigSlurper属性

[英]Spring Groovy Config: import ConfigSlurper properties

I'm trying to configure my Spring application using Groovy. 我正在尝试使用Groovy配置Spring应用程序。 I have several modules so the entire context is split to several .groovy files. 我有几个模块,因此整个上下文分为几个.groovy文件。

I use suggested method (section Using External Properties ) to read properties from external file using ConfigSlurper, so in my main context.groovy there's props object defined and used: 我使用建议的方法使用外部属性一节)使用ConfigSlurper从外部文件读取属性,因此在我的主要context.groovy ,定义并使用了props对象:

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

Where app.properties is: 其中app.properties是:

common {
    shiny = true
}

What I'm trying to do is to reuse the same properties source ( props object) in another context part anotherContext.groovy — something like: 我想做的是在另一个上下文部分anotherContext.groovy 重用相同的属性源( props对象)-类似于:

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

This code doesn't work as props is not available here, only beans from context.groovy . 此代码不起作用,因为这里没有props ,只有context.groovy bean。 Even when it is defined as a bean, the application fails to start with errors like Cannot get property 'shiny' on null object or No such property: for class... 即使将其定义为Bean,应用程序也无法启动,出现诸如Cannot get property 'shiny' on null objectNo such property: for class...

Please suggest if such configuration is possible. 请建议是否可以进行这种配置。 Thank you in advance! 先感谢您!

Property files are loaded through org.springframework.boot.context.config.ConfigFileApplicationListener , this happens before application context is really loaded. 属性文件是通过org.springframework.boot.context.config.ConfigFileApplicationListener加载的,这是在应用程序上下文真正加载之前发生的。

I made a custom GroovyPropertySource to load application.groovy on classpath, so it will be available to application context through the same Environment.getProperty() when it needs to configure. 我制作了一个自定义的GroovyPropertySource来在类路径上加载application.groovy ,因此在需要配置时,它可以通过相同的Environment.getProperty()用于应用程序上下文。

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

You should be able to do something like 你应该能够做类似的事情

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM