使用Spring注释注入父类依赖项的正确方法 [英] Proper way to inject parent class dependencies with Spring annotations
问题描述
我有以下代码-
Dao.java
@Component
public class Dao extends NamedParameterJdbcDaoSupport {
}
dbContext.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.jdbc.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.password}" />
</bean>
applicationContext.xml
<context:component-scan base-package="com.kshitiz" />
问题是NamedParameterJdbcDaoSupport
需要数据源才能工作.
由于这是超级类的属性,而不是我自己的类的属性,所以我想使它起作用的唯一方法是-
The problem is that NamedParameterJdbcDaoSupport
needs data source in order to work.
Since this is a property of the super class and not my own class the only way I could think of to make it work is -
@Component
public class Dao extends NamedParameterJdbcDaoSupport {
@Autowired
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
}
}
这很丑.我可以指定我要自动装配bean的所有属性吗?像-
This is pretty ugly. Can I specify that I want to autowire all the properties of my bean? Something like -
@Component(default-autowire="byType")
public class Dao extends NamedParameterJdbcDaoSupport {
}
春天有可能吗?另外,注入超类依赖项的最优雅的方法是什么?
Is this possible in Spring? Alternatively what is the most elegant way to inject super class dependencies?
修改: 我已经知道可以使用当前使用的XML来完成此操作.我想知道仅使用注释就可以做到的最好的事情.
I already know this can be done using XML which I am presently using. I'd like to know the best that can be done using annotations only.
推荐答案
不一定是您要寻找的答案,但是我会使用中介超类来做到这一点.
Not necessarily the answer you were looking for, but I would do this with an intermediary super class.
public abstract class AbstractDao extends NamedParameterJdbcDaoSupport {
@Autowired
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
}
}
@Component
public class Dao extends AbstractDao {
}
这篇关于使用Spring注释注入父类依赖项的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!