spring3.1使用JDBC数据源datasource的错误问题
JAR包:
junit-4.10.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.jdbc-3.1.1.RELEASE.jar
commons-logging.jar
mysql-connector-java-5.1.18-bin.jar
1、User类
Java code
package com.model;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2、UserDAO接口
Java code
package com.dao;
import com.model.User;
public interface UserDAO {
public void save(User u);
}
3、UserDAOImpl实现类
Java code
package com.dao.impl;
import java.sql.Connection;
import
java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.stereotype.Component;
import com.dao.UserDAO;
import com.model.User;
@Component("userDAO")
public class UserDAOImpl implements UserDAO {
private DataSource dataSource ;
public DataSource getDataSource() {
return dataSource;
}
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void save(User u) {
try {
Connection conn = dataSource.getConnection();
conn.createStatement().executeUpdate("insert into user values(null,'lisi')");
conn.close();
} catch (
SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("A user saved!");
}
}
4、UserService类
Java code
package com.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.dao.UserDAO;
import com.dao.impl.UserDAOImpl;
import com.model.User;
@Component("userService")
public class UserService {
private UserDAO userDAO = new UserDAOImpl();
public UserDAO getUserDAO() {
return userDAO;
}
@Resource(name="userDAO")
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public void add(User u) {
userDAO.save(u);
}
}
5、UserServiceTest测试类
Java code
package com.test;
import org.junit.Test;
import
org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.model.User;
impo