Please pardon me since I am a Spring beginner. I was following the example in the book but I only changed the database from Derby to MySQL.
My Main class is fairly simple:
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);
}
}
It creates a Data Access Object and try to add the new Vehicle object into the the DAO.The Vehicle class is very straightforward, an object class with four fields.
The VehicleDAO class is pasted here:
and my bean file is like:
<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>
As you can see above, I am always getting a null pointer error at line
conn= dataSource.getConnection();
So I suspect something is wrong with the MySQL connection, but I already included “mysql-connector-java-bin.jar” in the classpath in my Eclipse.
Thanks for any help in advance!
You have a typo in your setter
So when Spring injects the datasource, its value is not saved, I wonder if your IDE checks the source code for this kind of errors.
P.S. You should not open database connections manually in your DAO classes we have JdbcTemplate in Spring.