首页 > 解决方案 > 在 RowMapper 中自动装配 Objectmapper

问题描述

我发现答案说可以在 rowmapper 中自动装配,

如果您希望 ScoreMapper 实例将 ScoreCreator scoreCreator 注入 Spring bean,则 ScoreMapper 实例本身必须是 Spring bean,即。由 Spring 创建和管理

或者通过添加@Component

您可以将 PersonUtility 类定义为在类上添加 @component 的 spring bean。

但目前 RowMapper 是用 in 实例化newjdbcTemplate.query

jdbcTemplate.query(SQL, new Object[] {}, new MyRowMapper())

而且我不能在里面自动装配 Spring 管理的 ObjectMapper

public class MyRowMapper implements RowMapper<Map<Integer, Type>> {

   @Autowired
   @Qualifier("myObjectMapper")
   ObjectMapper objectMapper;

我应该如何重构当前代码来管理 bean 行映射器?

标签: javaspringjdbctemplaterowmapper

解决方案


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)
  }
}

请参阅此答案。它在类似的行中


推荐阅读