Daniil Penkin
Daniil Penkin

Reputation: 308

Spring Groovy Config: import ConfigSlurper properties

I'm trying to configure my Spring application using Groovy. I have several modules so the entire context is split to several .groovy files.

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:

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

Where app.properties is:

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:

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. 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...

Please suggest if such configuration is possible. Thank you in advance!

Upvotes: 0

Views: 933

Answers (1)

davidiamyou
davidiamyou

Reputation: 400

Property files are loaded through org.springframework.boot.context.config.ConfigFileApplicationListener, this happens before application context is really loaded.

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.

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

You should be able to do something like

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

Upvotes: 1

Related Questions