views:

358

answers:

2

Hi,

I'm currently in the process of building a CRUD tool for an existing Spring-based application. The application is being included in the Grails app as a JAR library which seems to work fine.

To make use of the library's own spring context, I used to load it through:

def ctx = new ClassPathXmlApplicationContext( 'classpath:/applicationContextName.xml')

in my service. Unfortunately the context builds its own datasource (the library's default) which is no good, as I need to use the dataSource defined in Grails.

So, my solution was to just include the library's spring configuration with the Grails context by adding an import to the grails-app\conf\spring\resources.xml file.

This seems to work (in so much as all beans are loaded into the same context and I can now autowire the beans straight in to my service classes by using def variableName.

Unfortunately, the dataSource defined in the library's spring config is overloading the dataSource defined in my Grails DataSource.groovy file!

Is there any way I can tell Grails to load the libary's spring configuration first, so that it then gets overridden by the rest of Grails config (and thus using Grails' DataSource)?

Thanks for your help,

James

...

As a tenporary measure, I've removed the dataSource entry in the dependancy's spring config file and its beans have been injected the dataSource created by the Grails config - this isn't ideal though, as I've had to make a 'special' build of the dependancy jar.

+1  A: 

Hi,

I'd look at making a trivial plugin containing your library and get it to load before the dataSources plugin (use def loadBefore = ['datasources'] in you *Plugin.groovy file).

Each plugin has a doWithSpring hook which lets you add beans to the context (you could include your existing context.xml there).

As an added bonus it will make it easier to re-use the library next time :)

cheers

Lee

leebutts
Good answer! I'm sure that would've solved the problem quite nicely. I no longer have two data sources (I removed the dependancy and re-coded the bits I needed) so unfortunately I can't test this out.
James Camfield
A: 

An easier solution can be import the context of the application in the Grails context (resources.xml) and then, there are two options. You can rename de datasource of the application to be different of the Grails one, or you can just delete the dataSource from the application and use the one of the Grails part Grails. The difference between the solutions is if the two datasources connect to the same database or not.

HED
There were two datasources because at the time, I needed to connect to two different databases. The temporary solution was what you suggested though - the datasource from the dependancy was named differently to the one defined in grails which allowed me to have 2.
James Camfield