Spring数据源bean在控制器中使用时给出空指针异常

时间:2013-01-12 10:47:09

标签: mysql spring nullpointerexception datasource

我在applicationContext.xml中使用spring的BasicDataSource,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byType">

    <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/school" />
        <property name="username" value="root" />
        <property name="password" value="" />
        <property name="initialSize" value="5" />
        <property name="maxActive" value="10" />
    </bean>
</beans>

当我在控制器中使用这个bean时如下:

package admin.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.inject.*;

@Controller
public class Welcome {

@Inject
BasicDataSource datasource;

private static final String WELCOME_PAGE = "welcome";

@RequestMapping("/")
public String welcome(ModelMap model){

    Connection con=null;
    PreparedStatement stmt =null;
    String testQuery = "INSERT INTO ADMIN(ID,USER_NAME,PASSWORD,FIRST_NAME,LAST_NAME) VALUES(?,?,?,?,?)";
    try {
        con = datasource.getConnection();
        stmt = con.prepareStatement(testQuery);

        stmt.setInt(1, 4);
        stmt.setString(2, "ij");
        stmt.setString(3, "kl");
        stmt.setString(4, "mn");
        stmt.setString(5, "op");

        stmt.execute();

        //con.commit();
    } catch (SQLException e) {
        e.printStackTrace();
    } 
    finally{
            try {
                if(con!=null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }
    return WELCOME_PAGE;
}   
}

然后它在行上给我一个nullpointer异常:datasource.getConnection();

连接细节是100%正确的,因为当我在控制器内创建一个新的BasicDatasource实例并使用其setter方法添加细节(例如:datasource.setDriverClassName等)时,它连接到数据库并执行查询而没有任何问题。但是当我想从应用程序上下文中使用bean时,它会给我一个空指针异常。

2 个答案:

答案 0 :(得分:0)

我没有理由我有空指针异常的原因。但我确信我在绑定中某处犯了错误。因为当我删除@Inject并为数据源实现setter方法时,我没有得到任何其他异常。并且事务成功完成。如果你能指明问题,请告诉我。

答案 1 :(得分:0)

我遇到了另一个有趣的事实,当我用@Autowired替换@Inject然后它工作正常,我不必写一个setter方法。但是,如果我使用@Inject,那么我必须编写一个setter方法来使其工作。这听起来很奇怪但在我的情况下似乎是正确的。