好吧,我在配置Spring的JDBCTemplate以正常工作时遇到了问题。我试图注入数据源,但它似乎总是为空。以下是示例代码:
的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>
的web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
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;
}
}
异常抛出:
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 :(得分:2)
我实际上是一个非常愚蠢的例外。 setDataSource()的主体是空的,即我没有将dataSource分配给任何东西,因此它总是为空。
愚蠢的我!!!