Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用接口的Springbean定义_Spring_Grails - Fatal编程技术网

使用接口的Springbean定义

使用接口的Springbean定义,spring,grails,Spring,Grails,更新:重复。看 我想通过它与Spring的接口来配置bean——正如我所期望的那样,在依赖注入框架中是可能的 以下是一个例子: public interface MyInterface { public void callMe(); } public class MyImpl implements MyInterface { public void callMe() { println("Calling MyImpl"); } } 例如,我应

更新:重复。看

我想通过它与Spring的接口来配置bean——正如我所期望的那样,在依赖注入框架中是可能的

以下是一个例子:

public interface MyInterface {
     public void callMe();
}

public class MyImpl implements MyInterface {
     public void callMe() {
          println("Calling MyImpl");
     }
}
例如,我应该如何配置这个bean,以便根据我是否在开发/生产环境中切换实现?在Grails中,我希望在Grails app/config/spring/resources.groovy中填充以下内容:

beans = {
     myBean(MyInterface) {
          implemented by MyImpl  //sintax not supported
     }
}
所以我可以在我的代码中定义和使用这个bean,比如:

def myBean
(...)
myBean.callMe()

我知道有一些Spring属性,如factory方法和factory bean可以实现这一点,但我想知道是否有一种简单而直接的接口方式可以在Spring/Grails中定义bean,而无需样板代码来实例化它们。

bean类型需要是一个非抽象类

beans = {
    myBean(MyImpl) {
        // ...  
    }
}

如果需要,您仍然可以基于接口类型进行DI,但是bean定义需要一个具体的类型。

这可能与grails环境的知识比Springbean更相关

要调用特定于环境的bean配置,您可以按如下方式执行:

环境。当前给出当前环境,从而

beans = {
     myBean(MyInterface) {
         if(Environment.current == Environment.DEVELOPMENT){
          implemented by MyImpl  
        }else{
          implemented by ProdImpl   
       }
     }
}

希望能有所帮助。

谢谢你的帮助,但我真正想知道的是“实施人…”中应该包含什么内容,而不是如何检查环境。我想也是这样。我能找到的最好的解决方案是: