Getting Spring IOC to work with the MVP pattern

吃可爱长大的小学妹 提交于 2019-12-11 10:27:33

问题


I'm attempting to use the MVP design pattern with a Swing application in conjunction with Spring IOC. In MVP the View needs to pass itself into the Presenter, and I can't work out how to do this with 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);

    }

}

This is my config xml (incorrect)

<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>

How do I get the View into the Presenter?


回答1:


You can override constructor arguments used for bean creation with BeanFactory.getBean(String name, Object... args). The shortcomings of this way are that lookup must be done by bean name rather than by its class, and that this method overrides all constructor arguments at once, so you have to use setter dependency for MyService:

 public class MainView  implements IMainView { 

    private MainPresenter _presenter; 

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

Also note the prototype scope, it's because each MainView needs its own 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>


来源:https://stackoverflow.com/questions/2037712/getting-spring-ioc-to-work-with-the-mvp-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!