【问题标题】:Autowire Objectmapper in RowMapper在 RowMapper 中自动装配 Objectmapper
【发布时间】:2020-04-09 02:03:57
【问题描述】:

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

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

或者通过添加@Component

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

但目前 RowMapper 是用 new in 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 行映射器?

【问题讨论】:

  • 您是否将您的 MyRowMapper 注释为 @Component - 如果是,您可以发布您遇到的异常吗?

标签: java spring jdbctemplate rowmapper


【解决方案1】:

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。类似的行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2013-11-12
    • 1970-01-01
    相关资源
    最近更新 更多