Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

java - Autowire Objectmapper in RowMapper

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...