RowMapper 中的自动装配 Objectmapper

Autowire Objectmapper in RowMapper

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

If you want ScoreMapper instances to have ScoreCreator scoreCreator be injected with a Spring bean, the ScoreMapper instance itself must be a Spring bean, ie. created and managed by Spring

或添加@Component

You can define PersonUtility class as spring bean adding @component over the class.

但目前 RowMapper 在 jdbcTemplate.query 中用 new 实例化:

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

而且我无法在内部自动装配 Spring 托管 ObjectMapper

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

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

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

RowMapper 是线程安全的 class。这意味着,它的单个实例可以在多个线程之间共享。所以,这意味着,你可以让它成为一个单例 class 并让 spring 处理它的生命周期(使用其中一个注释,如 @Component)。无论您想在哪里使用它的实例,只需 autowire/inject 个现有实例,而不是每次都实例化它 (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)
  }
}

参考这个 。它在相似的行