4

尝试设置我正在使用 Spring 3.0 的数据源时出现以下错误是我的代码:

错误

520  [ContainerBackgroundProcessor[StandardEngine[Catalina]]] ERROR org.springframework.web.context.ContextLoader  - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countryManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'countryDao' while setting bean property 'countryDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countryDao' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.crimetrack.jdbc.JdbcCountryDAO]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.crimetrack.jdbc.JdbcCountryDAO.<init>()

JdbcCountryDAO.java

@Repository
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO{

    private final Logger logger = Logger.getLogger(getClass());


    @Autowired
    JdbcCountryDAO(DataSource dataSource){
        setDataSource(dataSource);
    }

    public List<Country> getCountryList() {
        int countryId = 6;
        String countryCode = "AI";
        logger.debug("In getCountryList()");
        String sql = "SELECT * FROM TBLCOUNTRY WHERE countryId = ? AND countryCode = ?";
        logger.debug("Executing getCountryList String "+sql);

        Object[] parameters = new Object[] {countryId, countryCode};

        logger.info(sql);

        //List<Country> countryList = getJdbcTemplate().query(sql,new CountryMapper());

        List<Country> countryList = getJdbcTemplate().query(sql, parameters,new CountryMapper());
        return countryList;
    }

应用程序上下文.xml

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driverClassName}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    </bean>

  <bean id="countryManager" class="com.crimetrack.service.CountryManager">
        <property name="countryDao" ref="countryDao"/>
    </bean>
    <bean id="countryDao" class="com.crimetrack.jdbc.JdbcCountryDAO">
        <property name="dataSource" ref="dataSource"/>
    </bean>
4

2 回答 2

4

你需要这样做:

<bean id="countryDao" class="com.crimetrack.jdbc.JdbcCountryDAO">
    <constructor-arg index="0" ref="dataSource"/>
</bean>

dataSource不是类的属性,JdbcCountryDAO它是构造函数参数。Spring 对你说:No default constructor found,因为这不是默认构造函数:

@Autowired
JdbcCountryDAO(DataSource dataSource){
    setDataSource(dataSource);
}

它有一个DataSource作为参数。

于 2012-10-01T13:36:08.177 回答
0

我认为错误的原因很简单,因为您的 JdbcCountryDAO 的构造函数范围是默认范围,您需要将其设置为public.

于 2012-10-01T13:32:24.530 回答