dataSource没有获得任何价值。 dataSource.getConnection抛出java.lang.NullPointerException。
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" ></beans:property>
<beans:property name="url" value="jdbc:mysql://localhost:3306/mydb" ></beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="nannu"></beans:property>
</beans:bean>
<beans:bean id="vehicleDaoImpl" class="com.myapp.dataaccess.vehicle.VehicleDaoImpl">
<beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>
<context:component-scan base-package="com.myapp.dataaccess" />
public class VehicleDaoImpl implements VehicleDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource1) {
this.dataSource = dataSource1;
}
public void insert(Vehicle vehicle) {
String sql = "INSERT INTO Vehicle (VEHICLE_NO, COLOR, WHEEL, SEAT) "
+ "VALUES (?, ?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "gaurav");
ps.setString(2, "rai");
ps.setInt(3, 4);
ps.setInt(4, 7);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
@Override
public void update(Vehicle vehicle) { ... }
@Override
public void delete(Vehicle vehicle) { ... }
@Override
public Vehicle findByVehicleNo(String vehicleNo) {
return null;
}
}