将 RowMapper 类定义为 spring bean 可以吗?
在许多关于 Spring JDBC 的教程/书籍中,RowMapper 类通常表示为 DAO 内的私有静态最终类,并且在每个查询中创建实例。 RowMapper
是否必须以这种方式使用和实例化?
如果我使用 @Component
注释将 RowMapper
类定义为 spring bean,并将 @Autowired
定义为我的 dao 类,可以吗?
哪一个更好?
On many tutorial/books about spring JDBC, RowMapper
class usually represented as private static final class
inside DAO and the instance is created in every single query.
Does RowMapper
have to be used and instantiate in this way?
Is it ok if I define RowMapper
class as spring bean using @Component
annotation and @Autowired
it to my dao class?
Which one is better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这只是一种常见的使用模式。
当然,那会起作用。不过,除非 RowMapper 需要访问其他 Spring 服务,否则没有多大意义。
如果没有看到您的代码并了解您的应用程序,我们无法真正告诉您这是否是一个好主意,只有您可以做出选择。
我个人的偏好是将 RowMapper 保留为 DAO 类的非静态内部类,并直接从 DAO 实例化它。如果 RowMapper 需要访问其他 Spring bean,则将它们连接到 DAO 顶部,并从 RowMapper 内部类访问它们。
No, that's just a common usage pattern.
Sure, that would work. Unless the
RowMapper
needs access to other Spring services, though, there's not much point.Without seeing your code and getting a feel for your application, we can't really tell you if it's a good idea or not, only you can make that choice.
My personal preference would be to keep the
RowMapper
as a non-static inner class of your DAO class, and to insantiate it directly from the DAO. If theRowMapper
needs access to other Spring beans, then wire those intop the DAO, and access them from theRowMapper
inner class.