Autowire Objectmapper in RowMapper

落爺英雄遲暮 提交于 2019-12-24 23:08:21

问题


I found answers say it possible to autowire inside 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

Or by adding @Component

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

But currently RowMapper is instantiated with new in jdbcTemplate.query:

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

And I can't autowire Spring managed ObjectMapper inside

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

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

How should I refactor current code to manage bean row mapper?


回答1:


RowMapper is a thread safe class. That means, it's single instance can be shared amongst multiple threads. So, that means, you can let it be a singleton class and let spring handle it's lifecycle (Using one of those annotation like @Component). And wherever you want to use it's instance, just autowire/inject existing instance rather than instantiating it every time (new)

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

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

And then

class ASingletonClass(){
  @Autowired MyRowMapper myRowMapper;

  public MyRowMapper myAweSomeMethod(){
    return jdbcTemplate.query(SQL, new Object[] {}, myRowMapper)
  }
}

Refer this Answer. It's in similar lines



来源:https://stackoverflow.com/questions/59359496/autowire-objectmapper-in-rowmapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!