这是我在Grails中已经做过的非常简化的例子:
// this can be a service or normal class
public abstract class Person {
public final String introduceSelf() {
return "Hi, I'm " + getFullName()
}
protected abstract String getFullName()
}
// Service
class AlexService extends Person {
protected String getFullName() {
return "Alex Goodman"
}
}
// Service
class BobService extends Person {
protected String getFullName() {
return "Bob Goodman"
}
}
// Service
class CarlService extends Person {
protected String getFullName() {
return "Carl Goodman"
}
}
// Controller
class IntroduceController {
def alex
def bob
def carl
def index() {
if(params.person == "a")
render alex.introduceSelf()
if(params.person == "b")
render bob.introduceSelf()
if(params.person == "c")
render carl.introduceSelf()
}
}
我正在寻找更多面向对象的方式,例如:
// Controller
class IntroduceController {
def person
def index() {
// inject a proper person in a more object oriented way
render person.introduceSelf()
}
}
您能否建议如何以更加面向对象/动态的方式实现这一目标?
答案 0 :(得分:0)
您可以在person
文件中编写grails-app/conf/spring/resources.groovy
bean定义。例如:
beans = {
person(BobService)
}
有关详情,请查看:http://grails.org/doc/latest/guide/spring.html#springdslAdditional
答案 1 :(得分:0)
class IntroduceController {
def grailsApplication
def index() {
def person = grailsApplication.mainContext.getBean( params.person )
person.doSomething()
}
}
您必须确保您的服务名称与params.person
值相对应,params.person = 'bob'
可以使用,params.person = 'b'
不会