java - 在 RowMapper 中自动装配 Objectmapper
问题描述
我发现答案说可以在 rowmapper 中自动装配,
如果您希望 ScoreMapper 实例将 ScoreCreator scoreCreator 注入 Spring bean,则 ScoreMapper 实例本身必须是 Spring bean,即。由 Spring 创建和管理
或者通过添加@Component
您可以将 PersonUtility 类定义为在类上添加 @component 的 spring bean。
但目前 RowMapper 是用 in 实例化new
的jdbcTemplate.query
:
jdbcTemplate.query(SQL, new Object[] {}, new MyRowMapper())
而且我不能在里面自动装配 Spring 管理的 ObjectMapper
public class MyRowMapper implements RowMapper<Map<Integer, Type>> {
@Autowired
@Qualifier("myObjectMapper")
ObjectMapper objectMapper;
我应该如何重构当前代码来管理 bean 行映射器?
解决方案
RowMapper 是一个线程安全的类。这意味着,它的单个实例可以在多个线程之间共享。所以,这意味着,你可以让它成为一个单例类,让 spring 处理它的生命周期(使用像 @Component 这样的注释之一)。无论您想在哪里使用它的实例,只需自动装配/注入现有实例,而不是每次都实例化它(new
)
@Component
public class MyRowMapper implements RowMapper<Map<Integer, Type>> {
@Autowired
@Qualifier("myObjectMapper")
ObjectMapper objectMapper;
接着
class ASingletonClass(){
@Autowired MyRowMapper myRowMapper;
public MyRowMapper myAweSomeMethod(){
return jdbcTemplate.query(SQL, new Object[] {}, myRowMapper)
}
}
请参阅此答案。它在类似的行中
推荐阅读
- c++ - 在 C++ 字符串中查找完全匹配的单词
- mongodb - Mongodb计数数组中的项目组合
- amazon-web-services - 如何快速查看基于开始和结束日期的客户数量?
- python - 获取未存储在另一个列表中的嵌套列表
- python - 创建函数以查看哪些学生未通过该课程
- java - Firebase 存储通过引用获取图像
- flutter - 如何为 textStyle 创建 setter
- php - 无法与链接连接
- jenkins - 卷曲 - 带有新行的变量 - 非法的未引用字符代码 10
- javascript - 如何从数据库中获取数据并在 JavaScript、Ajax、MySQL 的 select2 下拉列表中显示?