RowMapper中的Autowire Objectmapper

问题描述 投票:0回答:1

[我发现answers说可以在rowmapper中自动接线,

[如果要让ScoreMapper实例将ScoreCreator scoreCreator注入Spring Bean,那么ScoreMapper实例本身必须是Spring Bean。由Spring创建和管理

或通过添加@Component

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

但是目前RowMapper已在new中以jdbcTemplate.query实例化:

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

而且我不能自动连接内部的Spring Managed ObjectMapper

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

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

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

java spring jdbctemplate rowmapper
1个回答
0
投票

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

参考此Answer。类似的行

© www.soinside.com 2019 - 2024. All rights reserved.