2012-07-17 170 views
2

獲取的NullPointerException與彈簧JDBC示例空指針異常而JdbcTemplate的

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

這是其中i得到的JdbcTemplate爲NULL的方法中,當我調用來自控制器findTotalCustomer方法。但是在服務器啓動時,它將值分配給數據源和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 o[email protected]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 [o[email protected]7ab2c6a6]: org.s[email protected]2d8e8541 
17 Jul, 2012 8:08:52 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons 
INFO: Pre-instantiating singletons in org.s[email protected]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---->[email protected]7968 
Updated Jdbctemplate---->[email protected]** 
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 
+0

「PersonDaoImpl」呢?是單身嗎? – 2012-07-17 15:03:01

+0

哪一條是第46行? – nook 2012-07-17 15:03:15

+0

@Nandkumar它不是一個單例類,dao實現類,想要使用jdbc訪問,但獲取null數據源 – Vicky 2012-07-17 15:06:29

回答

2

我的猜測是,春實例化的豆類和注入數據源,但不是從Spring bean工廠獲取bean,而是自己實例化一個bean,從而使用另一個實例,而不是在Spring的控制下,因此沒有使用DataSource進行初始化。

你永遠不應該做new SomeSpringBean()。所有的bean引用都應該注入依賴關係,或者通過向Spring bean工廠請求一個bean來獲得。

所以如果你的代碼的確是new PersonDaoImpl(),那麼有些地方是錯誤的。

+0

這是我的控制器方法代碼,其中ApplicationContext ctx = new FileSystemXmlApplicationContext(「classpath *:/ WEB-INF/springtutorial-servlet.xml」); \t \t PersonDaoImpl personDao = new PersonDaoImpl(); \t \t 如果\t(CTX!= NULL){ \t \t \t的PersonDAO =(PersonDaoImpl)ctx.getBean( 「的PersonDAO」); \t \t} \t \t \t \t \t \t personDao.findTotalCustomer(); – Vicky 2012-07-17 15:10:41

+0

ApplicationContext ctx = new FileSystemXmlApplicationContext(「classpath *:/ WEB-INF/springtutorial-servlet.xml」); \t \t PersonDaoImpl personDao = new PersonDaoImpl(); \t \t \t如果(CTX!= NULL){ \t \t \t的PersonDAO =(PersonDaoImpl)CTX。的getBean( 「的PersonDAO」); \t \t} \t \t \t \t \t \t personDao.findTotalCustomer(); – Vicky 2012-07-17 15:10:48

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");