Dependence on Grails dependencies outside of services?

I have a Grails application that should run a strategy, which is likely to be replaced over time. I know that Spring is at the heart of Grails, so I was wondering if I had access to the Spring IoC container so that I could export the actual dependency in an XML file (note: I never actually did that, but I just know about this, so I can miss something). My goal is to do something like the following:

class SchemaUpdateService { public int calculateSomething(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IStrategy strat = (IStrategy) ctx.getBean("mystrat"); } } 

And then map the appropriate implementation in the beans.xml file. I assume this is supported in Grails. Does anyone have documentation on how this will work? Do I really need a Spring IoC library and will it work? Thanks!

+7
source share
3 answers

You define your beans in resources.xml or resources.groovy . The graphics documentation gives an idea of ​​how to access the Spring application context.

+5
source

You can access the application context from any Grails artifact using

 ApplicationContext ctx = grailsApplication.mainContext 

Then you can use this to get the beans you are interested in:

 IStrategy strat = (IStrategy) ctx.getBean("mystrat") 

In classes that do not have access to grailsApplication , to access the application context and beans in it

You can use a helper assistant such as the following:
 class SpringUtils { static getBean(String name) { applicationContext.getBean(name) } static <T> T getBean(String name, Class<T> requiredType) { applicationContext.getBean(name, requiredType) } static ApplicationContext getApplicationContext() { ApplicationHolder.application.mainContext } } 

However, this is only necessary if you need to get different implementations of the same bean at runtime. If the required bean is known at compile time, just connect the beans together in resources.xml or resources.groovy

+4
source

First of all, you want to define your strategy in your grails-app/conf/spring/resources.groovy :

 beans = { myStrat(com.yourcompany.StrategyImpl) { someProperty = someValue } } 

Then you simply def property with the same name in your service:

 class SomeGrailsService { def myStrat def someMethod() { return myStrat.doSomething() } } 

In any Grails artifact (such as services and domain classes), Grails will automatically set the myStrat property myStrat correct value. But do not forget that in unit test you will have to specify this value manually, since automatic posting is not performed in unit tests.

Outside of the Grails artifact, you can use something like:

 def myStrat = ApplicationHolder.application.mainContext.myStrat 

In Grails 2.0, Graeme et al. Do not recommend using the *Holder classes (e.g. ApplicationHolder and ConfigurationHolder ), so I'm not quite sure what the Grails 2.0 approach will be ...

+4
source

All Articles