RowMapper中的Autowire Objectmapper [英] Autowire Objectmapper in RowMapper
问题描述
我发现答案说可以在内部自动接线行映射器
I found answers say it possible to autowire inside rowmapper,
如果您想让ScoreMapper实例具有一个Spring Bean注入ScoreCreator scoreCreator,那么ScoreMapper实例本身必须是一个Spring Bean,即.由Spring创建和管理
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 >
Or by adding @Component
您可以将PersonUtility类定义为spring bean,并在该类上添加@component.
You can define PersonUtility class as spring bean adding @component over the class.
但是当前RowMapper是用jdbcTemplate.query
中的new
实例化的:
But currently RowMapper is instantiated with new
in jdbcTemplate.query
:
jdbcTemplate.query(SQL, new Object[] {}, new MyRowMapper())
而且我无法自动将Spring托管的ObjectMapper接线
And I can't autowire Spring managed ObjectMapper inside
public class MyRowMapper implements RowMapper<Map<Integer, Type>> {
@Autowired
@Qualifier("myObjectMapper")
ObjectMapper objectMapper;
我应该如何重构当前代码来管理bean行映射器?
How should I refactor current code to manage bean row mapper?
推荐答案
RowMapper是线程安全的类.这意味着它的单个实例可以在多个线程之间共享.因此,这意味着,您可以将其设为单例类,并让spring处理其生命周期(使用@Component之类的批注之一).而且,无论您要使用它的实例是什么,都只需自动装配/注入现有实例,而不是每次都实例化(new
)
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;
然后
class ASingletonClass(){
@Autowired MyRowMapper myRowMapper;
public MyRowMapper myAweSomeMethod(){
return jdbcTemplate.query(SQL, new Object[] {}, myRowMapper)
}
}
请参考答案.在相似的行中
这篇关于RowMapper中的Autowire Objectmapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!