Search code examples
springgrailsspring-groovy-config

"Manually" creating beans with Grails BeanBuilder or Spring GenericGroovyApplicationContext


I have a class with complicated creation logic (e.g. uses builder). Back in 2000, because XML is rigid and not a programming language, I couldn't code the creation logic in it, so I encapsulated it in a FactoryBean.

Then the blessed JavaConfig came (thank you, @cbeams) and threw FactoryBean to the dumpster of history.

Since GroovyConfig is an additional step forward (not only a true programming language for the configuration, but also with DSL), I was sure to find a simple and elegant way to code my way though complicated creation logic, but didn't find any mention of an ability to do so?!

I understand that GroovyConfig is more or less taken verbatim from Grails BeanBuilder, so maybe if there is a way to do it there it will also work in GroovyConfig (fingers crossed).

Please tell me I am missing something obvious and don't have to use FactoryBean again!

Sleeping on it, I think the answer is no. I am adding an answer (still hoping it will get horribly downvoted as wrong one). Please prove me wrong!


Solution

  • Thinking about it, it looks like the answer is "no". It looks like I can't manage without FactoryBean, that's why:

    • XML and GroovyConfig are BeanDefinitionReaders. They are parsing the config files (XML and groovy script respectively) and creating BeanDefinition out of them. Whatever logic I code in the groovy script effects the BeanDefinition (e.g. I can wrap scope in if-else). Then, in later phase which I don't have the control of, Spring creates the bean objects based on the definition by itself.
    • JavaConfig is different. It's not parsed as a config file for BeanDefinition creation, but instead the objects created in it are the beans themselves (and the BeanDefinitions with them)! Which means that I have control in the time of bean creation and can implement any bean instance creation logic without FactoryBean, not only BeanDefinition logic.