Search code examples
springgrailsgrails-plugin

Datasource.groovy executed prior to application context loading?


I'm trying to implement a codec to decrypt a password for an Oracle data connection. The codec will be used in various locations, and I thought it might be a good idea to create a plugin for it. My idea was to create a codec that was aware of the Spring context, and could pull its salt phrase from Config.groovy. I have the Codec coded, and it's connecting at application startup - but it appears that my SpringContext.getApplicationContext() is returning null when the application starts up. I'm assuming this is because the application context hasn't been initialized yet - but my research isn't telling me much on the load order yet.

If that's the case, how would one go about externalizing something like this in configuration? The only way I know of to access DataSource information is through items like the grailsApplication reference (again Spring dependent).

Slightly Sanitized Code Snippet:

static Codec getCodec(){
    if( !SpringContext.getApplicationContext() ){
       println "Context Is Null"
    }
    def config = SpringContext?.getApplicationContext()?.
                                getBean("grailsApplication")?.config?.crypto
    String saltValue = config?.salt
    ...

Datasource.groovy is setup thusly:

datasource {
    ...some stuff
    passwordEncryptionCodec = 'com.someguy.mycode.StaticCodec'

Inside StaticCodec, I basically have encode/decode methods that call the factory method in the first code sample, they execute with no problem - and I receive the "Context Is Null" statement printed in the startup log after executing run-app.

SpringContext is a bean I've created in the doWithSpring section of my plugin, and seems to work fine outside of this startup issue (accessing the codec at request time works perfectly).

I had assumed the Spring container would be the first thing up and running when the application launched - am I wrong in this? Is there some other reason why the application context would be null when data sources are setting up at launch?


Solution

  • I had assumed the Spring container would be the first thing up and running when the application launched - am I wrong in this?

    Yes, you are.

    There are configuration files which have to be evaluated before the Spring container can be initialized because those config files define elements which will affect the initialization of the Spring container.