Spring 自动装配为 Abstract class 提供空 bean

Spring autowiring gives null bean for Abstract class

我正在尝试将 JDBCTemplate 注入(Autowire)到我的 Dao Class 中,这是一个 "Abstract class",这是行不通的,因为 spring 正在为 JDBCTemplate 提供 null bean。

public abstract class SSODaoImpl extends NamedParameterJdbcDaoSupport implements  SSODao{

    public SSODaoImpl(){

    }
    @Autowired //giving null jdbcTemplate
    public SSODaoImpl(JdbcTemplate jdbcTemplate){
    super.setJdbcTemplate(jdbcTemplate);
    }
}

SSODaoImpl 扩展了我的许多其他 DAO,如下所示

@Repository("askBenefitsDAO")
public class AskBenefitsSSODaoImpl extends SSODaoImpl{
}

我在文件 JDBCContext.xml 中创建了 bean 并在 web.xml

中引用了它
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
     <property name="jndiName" value="java:comp/env/jndi/hpdb_hrdb"/>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>

Web.xml

<context-param>
    <param-name> /WEB-INF/spring/JDBCTemplate/JDBCContext.xml</param-value>       
</context-param> 

启动应用程序时来自 spring 的错误消息

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'askBenefitsDAO' defined in file [AskBenefitsSSODaoImpl.class]: 
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required

以上设置适用于 "Non Abstract class" 设置。请帮助我,让我知道我做错了什么

原因是因为 spring 没有直接调用你的 SSODaoImpl class 的构造函数,而是 调用它的当 Spring 实例化 AskBenefitsSSODaoImpl class 时发生构造函数,因此 Spring 无法将 jdbcTemplate 绑定到您的 SSODaoImpl class.

您可以通过如下修改代码来实现:

@Repository("askBenefitsDAO")
public class AskBenefitsSSODaoImpl extends SSODaoImpl{
@Autowired 
    public AskBenefitsSSODaoImpl(JdbcTemplate jdbcTemplate){
    super(jdbcTemplate);
    }

}

public abstract class SSODaoImpl extends NamedParameterJdbcDaoSupport implements  SSODao{

    public SSODaoImpl(){

    }
    public SSODaoImpl(JdbcTemplate jdbcTemplate){
    super.setJdbcTemplate(jdbcTemplate);
    }
}