2010-01-10 41 views
1

我正在尝试将Swing应用与Spring IOC一起使用MVP设计模式。在MVP中,View需要将自己传递给Presenter,并且我无法弄清楚如何使用Spring做到这一点。让Spring IOC与MVP模式一起工作

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> 

我如何查看到演示?

+0

我不明白......你注释掉注入的观点到演示时,配置的部件,它是你在做什么问怎么做...什么给了? – skaffman 2010-01-10 17:02:03

+0

改变了问题,使其更清晰 - 我评论它不正确。 – Dan 2010-01-10 17:14:49

+0

好的,但该配置不是创建视图的新实例,而是将引用传递给现有的'MainView' bean – skaffman 2010-01-10 17:18:21

回答

2

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

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>