springgrailsgroovyspring-groovy-config

Making bean definitions in Groovy Bean Definition DSL order-independent


The only downside I currently see in the new Groovy Bean Definition DSL is that the beans in the closure must be declared in the dependency order. For example, while this works:

beans {
    repository(RepositoryImpl)
    service(ServiceImpl) {
        repository = repository
    }
}

This won't work:

beans {
    service(ServiceImpl) {
        repository = repository
    }
    repository(RepositoryImpl)        
}

That's because code in closure it executed line-by-line.

This is something we aren't used to in Spring - XML definition is parsed as a one DOM, in Java config the bean definitions are methods, so declaration order is not important.

I made some efforts to break this closure to mimic the Java config (closure/method per bean) but the code I came with was extremely ugly and verbose.

Do anyone has any idea how to refactor this closure to multiple order-independent units of code?

P.S. I understand that this definition style came from Grails, so maybe Grails community already has the answer?


Solution

  • The comment about using ref("repository") is a suggestion to accomplish what you are looking to do. Using ref instead of a variable name as you have in your example is the same as using the Spring ref attribute for a bean reference.

    You can read more about this, and other features of the Spring bean builder DSL in the documentation section for Grails and Spring.