Wednesday, August 7, 2013

Grails bean/service initialization dynamically to handle circular dependency

Suppose you have a service named OneService and another service named TwoService;
Now if you try to initiate TwoService in OneService and OneService in TwoService then you have some error regarding circular depency.

class OneService {
    def twoService;
}

class TwoService {
    def oneService;
}
To handle this you may need some trick.
First create a private static variable myTwoService and then initiate it when call it.

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA

class OneService {
    def ctx
    private static TwoService myTwoService;

    def getTwoService() {
        if(!ctx) {
            ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
        }
        if(!myTwoService) {
            myTwoService = ctx.getBean("twoService");
        }
        return myTwoService;
    }

    def someFunction = {
        def str = twoService.callSomeFunction();  
        /* it actually call getTwoService */
    }
}
And change you TwoService to call OneService such this way.

No comments:

Post a Comment