0
請原諒我,因爲我是Spring初學者。我正在關注本書中的示例,但我只是將數據庫從Derby更改爲MySQL。在Spring中使用JDBC時遇到空指針異常
我的主類是相當簡單:
public class Main {
public static void main(String [] args)
{
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
VehicleDAO dao= (VehicleDAO) context.getBean("vehicleDao");
Vehicle vehicle = new Vehicle("TEM0001", "Red", 4, 4);
dao.insert(vehicle);
}
}
它創建了一個數據訪問對象,並嘗試新的車輛對象添加到該DAO.The Vehicle類是非常簡單的,一個具有四個字段的對象類。
的VehicleDAO類粘貼在這裏:
和我Bean文件是這樣的:
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="org.gjt.mm.mysql.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/vehicle" />
<property name="username" value="root" />
<property name="password" value="3324911" />
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="vehicleDao"
class="com.apress.springrecipes.vehicle.JdbcVehicleDao">
<property name="dataSource" ref="dataSource" />
</bean>
正如你可以在上面看到,我總是得到的線空指針錯誤
conn= dataSource.getConnection();
所以我懷疑M有些問題ySQL連接,但我已經在Eclipse的classpath中包含了「mysql-connector-java-bin.jar」。
感謝您提前提供任何幫助!
你檢查過日誌嗎?正如你猜測的那樣,dataSource bean可能沒有被適當的初始化。需要更多信息。 – dgregory