使Spring IOC与MVP模式一起使用

编程入门 行业动态 更新时间:2024-10-27 14:31:28
本文介绍了使Spring IOC与MVP模式一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将 MVP 设计模式与Swing一起使用与Spring IOC结合使用.在MVP中,View需要将自身传递给Presenter,而我无法弄清楚如何使用Spring.

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); } }

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

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?

推荐答案

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

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); } }

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

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>

更多推荐

使Spring IOC与MVP模式一起使用

本文发布于:2023-11-08 09:37:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569021.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   Spring   IOC   MVP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!