Showing posts with label loadBean. Show all posts
Showing posts with label loadBean. Show all posts

Friday, January 21, 2022

Splitting resources.groovy configuration in Grails applications

Splitting resources.groovy configuration in Grails applications

1. Introduction:

In grails, when our resources.groovy file is growing then it is better to split some logical bean configuration with a separate file and import that file in resources.groovy.  For this, Grails provides a neat way to specify Spring bean definitions with its custom Beans DSL by using importBeans or loadBeans.

2. How to split resources.groovy

You can simply create resources file under  "grails-app/conf/spring/" package: e.g

firstBean.groovy:
beans {
  beanConfiguration: yourBeanConfiguration
}

3. Import external bean file

Grails provide importBeans or loadBeans to import custom external bean file which can be done inside resources.groovy as bellow:
beans = { 
  importBeans('file:grails-app/conf/spring/firstBean.groovy') 
}

The problem is that this seems to work, but only if you run the application via  grails run-app with the embedded servlet container.

As soon we create a WAR file and deploy it into tomcat we are getting into trouble. The problem is Spring Bean Configuration file is moved on the different folder in tomcat "WEB-INF/classes/spring/" so we can get file-not-found-exception.

In order to resolve this problem, we need to locate custom resource path in resources.groovy.
def loadFromFile = { name ->
        importBeans("file:grails-app/conf/spring/"+name)
    }

    def loadFromWar = { name ->
        def resource = application.parentContext.getResource("WEB-INF/classes/spring/"+name)
        loadBeans(resource)
    }
    def loadResource = application.isWarDeployed() ? loadFromWar : loadFromFile

    loadResource "firstBean.groovy"
    loadResource "secondBean.groovy"



Here if the application is running via grails run-app then it will use the path "grails-app/conf/spring/". And if it is via external tomcat with deploying the WAR file then it uses the path "WEB-INF/classes/spring/".

Note: Be sure that your resource file is packaged on WAR with the right path.
Share: