views:

1173

answers:

1

Hi! I have a grails / groovy application running under tomcat. For some reason I have to be able to change the application context dynamically. That is, I want to be able (at login time) to set this context.

I know that this is doable via the Config.groovy but this is static. At login time I am getting a parameter which is the context for the application.

How can I set this context?

Thanks in advance.

Luis

+3  A: 

Typically, you wouldn’t need to change application context on each user login. Spring Context contains objects that typically live as long as the application and are generally not user-dependent. Maybe you wish to expand your question and explain your scenario since based on what you said so far it doesn’t seem that you are on the right track.

In one application, we had a different data source depending on the enterprise that user belonged. Even than, context was not affected, only the user session and a bit of meddling with OpenSessionInView filter.

If, for whatever reason, you need to intervene the Spring ApplicationContext programmatically, you can do it by getting hold of Context by the means of ApplicationContextAware interface. Then you can manipulate the context, for example add new bean definitions, chain contexts (see setParent) etc.

You can use BeanDefinitionBuilder to construct your bean and then call the registerBean method on GenericApplicationContext.

You can get a hold of ApplicationContext by making your service for example ApplicationContextAware. Then you can invoke registerBean method from your controller. Take a look at this code:

import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.beans.factory.support.BeanDefinitionBuilder

class MyRedefiningService implements ApplicationContextAware {

def context

void setApplicationContext(ApplicationContext context) { 
    this.context = context
}

void registerBean(){
    BeanDefinitionBuilder builderA = BeanDefinitionBuilder
.rootBeanDefinition(DummyService.class)
    context.registerBeanDefinition("bean-a", builderA.getBeanDefinition());
    println context.getBean("bean-a");

    }
}

//controller class
class SomeController {

   def myRedefining

   def index = {
       myRedefining.registerBean()
   }

}
Dan
I really do not understand exactly how to use your hint. I really would appreciate if you can specify a little bit more how to use your approach.Thanks a lot. Luis
Luixv
I expanded my answer. If it is still not clear, maybe it is best if you describe the problem you are facing in more detail.
Dan