【问题标题】:Getting Spring IOC to work with the MVP pattern让 Spring IOC 使用 MVP 模式
【发布时间】:2010-01-10 16:58:28
【问题描述】:

我正在尝试将MVP 设计模式与Swing 应用程序结合使用Spring IOC。在 MVP 中,View 需要将自身传递给 Presenter,而我不知道如何使用 Spring 来做到这一点。

public class MainView  implements IMainView {

    private MainPresenter _presenter;

    public MainView() {

        _presenter = new MainPresenter(this,new MyService());

       //I want something more like this
       // _presenter = BeanFactory.GetBean(MainPresenter.class);

    }

}

这是我的配置 xml(不正确)

<bean id="MainView" class="Foo.MainView"/>
<bean id="MyService" class="Foo.MyService"/>

<bean id="MainPresenter" class="Foo.MainPresenter">
    <!--I want something like this, but this is creating a new instance of View, which is no good-->
   <constructor-arg type="IMainView">
        <ref bean="MainView"/>
    </constructor-arg>
    <constructor-arg  type="Foo.IMyService">
        <ref bean="MyService"/>
     </constructor-arg>
</bean>

如何让 View 进入 Presenter?

【问题讨论】:

  • 我不明白...您已经注释掉了将视图注入演示者的配置部分,这就是您要问的如何做...什么给出了?
  • 更改了问题以使其更清晰 - 我将其注释为不正确。
  • 好的,但是该配置没有创建视图的新实例,它传递了对现有 MainView bean 的引用

标签: java spring ioc-container mvp


【解决方案1】:

您可以使用BeanFactory.getBean(String name, Object... args) 覆盖用于创建 bean 的构造函数参数。这种方式的缺点是必须通过 bean 名称而不是其类来查找,并且此方法一次覆盖所有构造函数参数,因此您必须使用 MyService 的 setter 依赖项:

 public class MainView  implements IMainView { 

    private MainPresenter _presenter; 

    public MainView() { 
        _presenter = beanFactory.getBean("MainPresenter", this); 
    }  
}

还要注意prototype 范围,这是因为每个MainView 都需要自己的MainPresenter

<bean id="MyService" class="Foo.MyService"/>   

<bean id="MainPresenter" class="Foo.MainPresenter" scope = "prototype">   
    <constructor-arg type="IMainView"><null /></constructor-arg>   
    <property name = "myService">   
        <ref bean="MyService"/>   
    </property>   
</bean>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多