我仍然不明白如何避免使用 getBean()
我是 Spring 的新手,我读过很多关于如何注入 bean 的指南。奇怪的是,在我看到的每个示例中,他们在类 main 方法中使用 getBean (不是我需要的)。此外,我还阅读了许多与如何不使用 getBean 相关的论坛和问题,但我仍然无法找出适合我的应用程序的最佳方法。
我正在重构一个高度耦合且没有设计模式的 Web 应用程序。每个业务类都有一个相应的 DAO 类,每个 DAO 类都扩展一个超级 DAO 来处理连接和其他内容。这里的问题是每个 DAO 在构造函数中都需要一些从业务类传递的数据库配置参数。我想做的是将这些参数放入 DBConfig bean 中,并将它们注入到每个 DAO 中,从而允许我简单地从每个业务类创建 DAO 对象,例如:dao =新的 myDAO()。
如何“自动”将DBConfig bean 注入到每个 DAO 中?我应该在超级 DAO 中使用getBean吗?
I'm new to Spring and I've read many guides on how to inject beans. Curiously, in every example I see, they use getBean in a class main method (not what I need). Also I've read many forums and questions related to how not to use getBean but I still can't figure out the best approach for my app.
I'm refactoring a web app that is highly coupled and without design patterns. Every business class has a corresponding DAO class, every DAO class extends a super DAO which handles the connection and other stuff. The problem here is that every DAO needs, in the constructor, some database config parameters that are being passed from the business class. What I'm trying to do is to put these parameters in a DBConfig bean and inject them into every DAO allowing me to create the DAO object from every business class simply, for example: dao = new myDAO().
How can I inject the DBConfig bean into every DAO "automatically"? Should I use getBean in the super DAO?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的配置可能如下所示:
或者在所有
daoX
beans 之间共享一个daoConfig
实例,如果您想要的话。然后,您可以使用以下代码来处理业务逻辑:
或者更好的是,使用 Spring MVC 之类的东西可以将业务 bean 连接到控制器中,而无需调用 getBean() 。
Your config could look like this:
Or share a single
daoConfig
instance between alldaoX
beans, if that's what you want.You can then use the folowing to handle the business logic:
Or better still, use something like Spring MVC that can wire the business beans into your controllers without needing to call
getBean()
.