spring - 依赖注入(inject) : conditional

标签 spring grails

这是我已经在 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()
    }
}

您能否建议如何以更加面向对象/动态的方式实现这一目标?

最佳答案

你可以写一个person grails-app/conf/spring/resources.groovy 中的 bean 定义文件。例如:

beans = {
    person(BobService)
}

欲了解更多信息,请查看:http://grails.org/doc/latest/guide/spring.html#springdslAdditional

关于spring - 依赖注入(inject) : conditional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21753293/

相关文章:

java - 创建名称为 'cxf' 的 bean 时出错

java - 从 portlet 将图像上传到 liferay 主题

java - 如何将 org.springframework 中的 XML bean 转换为注释

grails - 如何重定向到关于拒绝 Spring 安全访问的上一页?

grails - Grails url映射从sperate配置文件传递数据

grails - Grails 2.0.0的就地插件

java - jasper grails 插件升级到 Java8 失败

java - 需要帮助来理解 spring 配置文件

spring - Liquibase includeAll 标签被忽略

tomcat - 如何找到tomcat网络应用程序的网址?