Showing posts with label grails. Show all posts
Showing posts with label grails. Show all posts

Adding a new node to an XML file in Groovy

Whilst working on a Grails plugin I needed to add an extra import statement to the Spring resources.xml config file, here's how I did it.


def parser= new XmlParser().parse(new File('resources.xml'))

if (!parser.'import'.'@resource'.contains('foo.xml')) {
def newNode = new Node(res, 'import', [resource: 'foo.xml'])
res.'import'.add(newNode)
}

def writer = new FileWriter('resources.xml')
new XmlNodePrinter(new PrintWriter(writer)).print(parser)

Loading Spring XML Config Files in a Grails Plugin

If your Grails plugin needs to load Spring config from a JAR that it depends on you can do this is the doWithApplicationContext hook.

def doWithApplicationContext = { applicationContext ->

XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
xmlReader.loadBeanDefinitions(new ClassPathResource("foo-config.xml"));
}

Setting up Spring Aliases in a Grails plugin

There are two places in a plugin where you can define an alias, doWithSpring and doWithApplicationContext.

In doWithSpring there is a variable called springConfig which is a RuntimeSpringConfiguration. You can use it like this:

springConfig.addAlias "myAliasedName", "myBeanName"


In doWithApplicationContext you can use the applicationContext which is passed into the closure like this:

applicationContext.registerAlias("myBeanName", "myAliasedName")

Echo Spring beans names in doWithApplicationContext for debug purposes

In a Grails plugin doWithApplicationContext closure you may find it useful to see what Spring beans have been built by you doWithSpring closure.


applicationContext.beanDefinitionNames.each {
println "Spring Bean: " + it
}