Yesterday I've read, the post from Josh Creed about a pluggable service in Grails and I've been thinking the way to do with IoC and wire provider with Spring.
Let's do it, with small test.
First my service class GreetService:
class GreetService {
def provider
def sayHello(String name){
provider.sayHello(name)
}
}Now, two Providers:
class DevProvider {
def sayHello(String name){
println "DevProvider: hello ${name}"
}
}
class TestProvider {
def sayHello(String name){
println "TestProvider: hello ${name}"
}
}Now I'm gonna use Spring DSL, in
resources.groovy, to define
provider bean that depends of environment:
import grails.util.*
beans = {
switch(GrailsUtil.environment) {
case "test":
provider(TestProvider)
break
case "development":
provider(DevProvider)
break
}
}
And that's all with Groovy and Grails magic, here the test:
class GreetServiceTests extends GroovyTestCase {
def greetService
void testGreet() {
greetService.sayHello("World!!!!!!")
}
}
// output: TestProvider: hello World!!!!!!
And in Grails console, another test:
def service = ctx.getBean("greetService")
service.sayHello("world")
// output: DevProvider: hello world