将 RowMapper 类定义为 spring bean 可以吗?

发布于 2025-01-02 06:33:22 字数 258 浏览 0 评论 0原文

在许多关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慕烟庭风 2025-01-09 06:33:22

是否必须以这种方式使用和实例化RowMapper

不,这只是一种常见的使用模式。

如果我使用@Component注释将RowMapper类定义为spring bean,并将@Autowired它定义为我的dao类,可以吗?

当然,那会起作用。不过,除非 RowMapper 需要访问其他 Spring 服务,否则没有多大意义。

哪个更好?

如果没有看到您的代码并了解您的应用程序,我们无法真正告诉您这是否是一个好主意,只有您可以做出选择。

我个人的偏好是将 RowMapper 保留为 DAO 类的非静态内部类,并直接从 DAO 实例化它。如果 RowMapper 需要访问其他 Spring bean,则将它们连接到 DAO 顶部,并从 RowMapper 内部类访问它们。

Does RowMapper have to be used and instantiate in this way

No, that's just a common usage pattern.

Is it ok if I define RowMapper class as spring bean using @Component annotation and @Autowired it to my dao class?

Sure, that would work. Unless the RowMapper needs access to other Spring services, though, there's not much point.

Which one is better?

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 the RowMapper needs access to other Spring beans, then wire those intop the DAO, and access them from the RowMapper inner class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文