2010-01-28 56 views
2

嗯,我有配置Spring的JdbcTemplate正常工作的問題。我正在嘗試注入數據源,但似乎它始終爲空。下面是一個示例代碼:春天的JdbcTemplate拋出:IllegalArgumentException:數據源需要

  1. applicationContext.xml中:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
    <property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" /> 
    <property name="url" 
        value="jdbc:derby:c:\\Derby\\MyDB\\jsfkickstart;create=true" /> 
    <property name="username" value="admin" /> 
    <property name="password" value="admin" /> 
    </bean> 
    
    <bean id="employeeDoa" class="com.kickstart.employeeapp.doa.EmployeeDoa"> 
        <property name="dataSource" ref="dataSource" /> 
    </bean> 
    
  2. 的web.xml

    <context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/applicationContext.xml</param-value> 
    

    ​​
  3. EmployeeDoa.java

    public class EmployeeDoa implements IEmployeeDoa, IDepartmentDoa { 
    private DataSource dataSource; 
         public List<Employee> getAllEmployees() { 
         JdbcTemplate select = new JdbcTemplate(dataSource); 
         return select.query(
           "SELECT "+ 
            "e.ID as empId, "+ 
            "e.FIRSTNAME as empFirstName, "+ 
            "e.LASTNAME as empLastName, "+ 
            "d.ID as depId, "+ 
            "d.NAME as depName, "+ 
            "d.LOCATION as depLocation "+ 
           "FROM jsfkickstart.Employee e, jsfkickstart.Department d", 
           new EmployeeMapper()); 
         } 
    } 
    
    class EmployeeMapper implements RowMapper { 
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException { 
         Employee emp = new Employee(); 
         emp.setId(rs.getInt("empId")); 
         emp.setFirstName(rs.getString("empFirstName")); 
         emp.setLastName(rs.getString("empLastName")); 
         Department dep = new Department(); 
         dep.setId(rs.getShort("depId")); 
         dep.setLocation(rs.getString("depLocation")); 
         dep.setName(rs.getString("depName")); 
         emp.setDepartment(dep); 
         return emp; 
        } 
    } 
    
  4. 拋出異常:

    Exception in thread "main" java.lang.IllegalArgumentException: Property 'dataSource' is required 
    at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134) 
    at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:142) 
    at com.kickstart.employeeapp.doa.EmployeeDoa.addEmployee(EmployeeDoa.java:29) 
    

有誰知道我怎麼能解決這個問題呢?如果我錯過了問題中的任何重要信息,請告訴我。

謝謝。

+0

給com.kickstart.employeeapp.doa.EmployeeDoa的代碼(至少在類聲明) – Bozho 2010-01-28 11:32:50

+0

加入!謝謝Bazho。 – fouad 2010-01-28 11:52:32

回答

2

我其實是一個非常愚蠢的例外。 setDataSource()的主體是空的,即我沒有將dataSource賦值給任何東西,所以它始終爲空。

愚蠢的我!

+0

我打算說我根本沒有看到setDataSource()方法。 – Matt 2010-01-28 19:41:20

+0

是非常愚蠢的;) – Mils 2013-03-05 22:54:12

相關問題