2

使用 spring jdbc 示例获取 NullPointerException

java.lang.NullPointerException
    at com.net.technicalkeeda.dao.PersonDaoImpl.findTotalCustomer(PersonDaoImpl.java:46)

当我从控制器调用 findTotalCustomer 方法时,这是我将 jdbcTemplate 设为 NULL 的方法。但是在服务器启动时,它会为数据源和 jdbctemplate 分配值。所以你能帮我解释一下为什么会有一个 NULL 值。

这是我的控制器类,我正在访问 dao 方法

public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:/WEB-INF/springtutorial-servlet.xml");

        if (ctx != null) {
            personDao = (PersonDaoImpl)ctx.getBean("personDao");
        }


        personDao.findTotalCustomer();

        return new ModelAndView("hello.jsp");
    }

}
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
        <property name="url"><value>jdbc:mysql://localhost:3306/technicalkeeda</value></property>
        <property name="username"><value>root</value></property>
        <property name="password"><value></value></property>
    </bean>

    <bean id="personDao" class="com.net.technicalkeeda.dao.PersonDaoImpl">
    <property name="dataSource"><ref local="dataSource" /></property>
    </bean>



package com.net.technicalkeeda.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.net.technicalkeeda.bean.Person;

/**
 * @author Yashwant Chavan
 * 
 */
public class PersonDaoImpl {


    private DataSource dataSource;

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplate = new JdbcTemplate(dataSource);

        System.out.println("Updated Datasouce---->" + dataSource);
        System.out.println("Updated Jdbctemplate---->" + jdbcTemplate);
    }

    /* Display all persons */
    public Collection<Person> findAll() {
        System.out.println("Calling............." + this.jdbcTemplate);
        return jdbcTemplate.query(
                "select emp_name, emp_salary from trn_employee",
                new PersonMapper());

    }

    public int findTotalCustomer(){

        String sql = "SELECT COUNT(*) FROM trn_employee";
        System.out.println("jdbcTemplate" + jdbcTemplate);
        int total = jdbcTemplate.queryForInt(sql);

        return total;
    }

    private static final class PersonMapper implements RowMapper {

        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Person person = new Person();
            person.setFirstName(rs.getString("emp_name"));
            return person;
        }
    }

}

控制台日志

17 Jul, 2012 8:08:52 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(C:\javaworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringTutorial\WEB-INF\lib\j2ee.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
17 Jul, 2012 8:08:52 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springtutorial'
17 Jul, 2012 8:08:52 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'springtutorial': initialization started
17 Jul, 2012 8:08:52 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.XmlWebApplicationContext@7ab2c6a6: display name [WebApplicationContext for namespace 'springtutorial-servlet']; startup date [Tue Jul 17 20:08:52 IST 2012]; root of context hierarchy
17 Jul, 2012 8:08:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/springtutorial-servlet.xml]
17 Jul, 2012 8:08:52 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext@7ab2c6a6]: org.springframework.beans.factory.support.DefaultListableBeanFactory@2d8e8541
17 Jul, 2012 8:08:52 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2d8e8541: defining beans [dataSource,personDao,helloController,loggerInterceptor,performanceInterceptor,urlMapping]; root of factory hierarchy
17 Jul, 2012 8:08:53 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
**Updated Datasouce---->org.springframework.jdbc.datasource.DriverManagerDataSource@38827968
Updated Jdbctemplate---->org.springframework.jdbc.core.JdbcTemplate@7df0b7d3**
17 Jul, 2012 8:08:53 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'springtutorial': initialization completed in 453 ms
17 Jul, 2012 8:08:53 PM org.apache.coyote.http11.Http11BaseProtocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
17 Jul, 2012 8:08:53 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
17 Jul, 2012 8:08:53 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/0  config=null
17 Jul, 2012 8:08:53 PM org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry server-registry.xml at classpath resource
17 Jul, 2012 8:08:53 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1749 ms
4

2 回答 2

2

我的猜测是 Spring 实例化它的 bean 并注入 DataSource,但不是从 Spring bean factory 获取 bean,而是您自己实例化一个,因此使用另一个实例,不受 Spring 的控制,因此没有使用 DataSource 初始化。

你不应该这样做new SomeSpringBean()。所有的 bean 引用都应该被注入依赖或者应该通过向 Spring bean 工厂询问一个 bean 来获得。

因此,如果您的代码确实如此new PersonDaoImpl(),则说明有问题。

于 2012-07-17T15:06:10.837 回答
0

我会冒险猜测并说您没有正确地将 bean 从上下文文件中取出。新的运算符和弹簧玩得不好。我假设你知道如何从 中取出豆子application-context.xml,但如果不知道,我还是把它留在这里。

    //simple singleton
    private static void initApplicationContext() {
    if (_applicationContext == null)
        _applicationContext = new ClassPathXmlApplicationContext("PersistenceHelper-context.xml");
}
//get bean
Datasource dataSource = (DataSource) _applicationContext.getBean("dataSource");
于 2012-07-17T15:15:14.690 回答