我正在学习 Spring 如何支持多线程。我发现Spring文档说JdbcTemplate是thread-safe一旦配置完成。 人们建议为整个应用程序使用一个 JdbcTemplate 实例,因为它是线程安全的(意味着无需为每个类创建一个新实例)。
但是当我查看 JdbcTemplate 代码时,我没有看到任何同步方法、锁或 volatile 变量。它还包含很多实例变量。我的问题是在这种情况下 JdbcTemplate 如何是线程安全的?
最佳答案
这是 Spring 引用文档 JDBCTemplate Best Practices 部分下的片段
Instances of the JdbcTemplate class are thread-safe, once configured. This is important because it means that you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs (or repositories). The JdbcTemplate is stateful, in that it maintains a reference to a DataSource, but this state is not conversational state.
正如文档中清楚地解释的那样,您也可以在源代码中看到。该类不保持任何 session 状态。它只有配置信息。
关于java - 为什么Spring JdbcTemplate是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55454249/