2017-04-14 138 views
-1

在它工作之前,現在它不工作。以前它工作時我使用CrediCarddao.java中的會話NULL來更新客戶狀態並將新的信用卡記錄插入到數據庫中。警告:在上下文初始化期間遇到的異常

2017年4月14日上午09點32分36秒org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh INFO:刷新org.[email protected]68de145:啓動日期[週五09年4月14日: 32:36 CDT 2017];上下文層次結構的根 2017年4月14日上午9時32分36秒org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息:從文件[C:\ BCJ_DEC_2016 \ workspace \ CoreJava \ creditcardprocess \ spring中加載XML bean定義。 XML] 2017年4月14日上午09點32分37秒org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache 信息:尋找@ControllerAdvice:org.[email protected]68de145:啓動日期[週四4月14日09:32:36 CDT 2017];上下文層次結構的根 2017年4月14日上午9:32:37 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache 信息:尋找@ControllerAdvice:org.[email protected]68de145 :啓動日期[Fri Apr 14 09:32:36 CDT 2017];上下文層次結構的根 2017年4月14日上午9時32分37秒org.springframework.context.support.FileSystemXmlApplicationContext刷新 警告:在上下文初始化期間遇到異常 - 取消刷新嘗試:org.springframework.beans.factory.BeanCreationException:創建錯誤在文件[C:\ BCJ_DEC_2016 \ workspace \ CoreJava \ creditcardprocess \ target \ classes \ com \ bcj \ creditcardprocess \ dao \ CreditCardDao.class]中定義了名爲'creditCardDao'的bean:bean實例化失敗;嵌套異常是org.springframework.beans.BeanInstantiationException:未能實例化[com.bcj.creditcardprocess.dao.CreditCardDao]:構造函數拋出異常;嵌套異常是java.lang.NullPointerException 線程「main」中的異常org.springframework.beans.factory.BeanCreationException:在文件[C:\ BCJ_DEC_2016 \ workspace \ CoreJava \ creditcardprocess \ target \中定義名稱'creditCardDao' class \ com \ bcj \ creditcardprocess \ dao \ CreditCardDao.class]:bean的實例化失敗;嵌套異常是org.springframework.beans.BeanInstantiationException:未能實例化[com.bcj.creditcardprocess.dao.CreditCardDao]:構造函數拋出異常;嵌套的異常是在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java顯示java.lang.NullPointerException 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) : 1099) 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) 在有機springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegist ry.getSingleton(DefaultSingletonBeanRegistry.java:230) 在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) 在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory。的java:197) 在org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) 在org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) 在有機springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org。(FileSystemXmlApplicationContext.java:140) at org.springframework.context.support.FileSystemXmlApplicationContext。(FileSystemXmlApplicationContext.java:84) at com.bcj.creditcardprocess.CreditCardMain.main(CreditCardMain.java: 15) 引起:org.springframework.beans.BeanInstantiationException:無法實例化[com.bcj.creditcardprocess.dao.CreditCardDao]:構造函數拋出異常;嵌套的異常是在org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)顯示java.lang.NullPointerException 在org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ...... 13多個 引起的:在com.bcj.creditcardprocess.dao.CreditCardDao(CreditCardDao顯示java.lang.NullPointerException 。 java:22) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) a (java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ) ...... 15多個

CreditCardMain.java *

package com.bcj.creditcardprocess; 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.FileSystemXmlApplicationContext; 

import com.bcj.creditcardprocess.service.CreditCardService; 

public class CreditCardMain {  

    public static void main(String[] args) {  

     @SuppressWarnings("resource") 
     ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml"); 

     CreditCardService obj = (CreditCardService) context.getBean("cCardService"); 
     //CreditCardService cCardService = new CreditCardService(); 

     obj.processCreditCard();  
    }  
} 

CreditCardService.java

package com.bcj.creditcardprocess.service; 

import java.util.Iterator; 
import java.util.List; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 

import com.bcj.creditcardprocess.dao.CreditCardDao; 
import com.bcj.creditcardprocess.model.Customer; 


@Service 
public class CreditCardService { 

    @Autowired 
    private CreditCardDao cCardDao; 

    public void setcCardDao(CreditCardDao cCardDao) { 
     this.cCardDao = cCardDao; 
    } 

    public void processCreditCard() { 

     List<Customer> customerList = cCardDao.getCustomerList(); 
     // creating a pool of 5 threads 

     ExecutorService executor = Executors.newFixedThreadPool(5); 
     for (Iterator iterator = customerList.iterator(); iterator.hasNext();) { 
      Customer cust = (Customer) iterator.next(); 
      System.out.println(cust); 

      WorkerThread thread = new WorkerThread(); 
      thread.threadmain(customerList); 
      //Runnable worker = new WorkerThread(cust); 

      // calling execute method of ExecutorService 

      //executor.execute(worker); 
/*WorkerThread thread = new WorkerThread(); 
thread.threadmain(customerList); 
     } 
     executor.shutdown(); 
     while (!executor.isTerminated()) { 
     } 

     System.out.println("Finished all threads");*/ 

     /* 
     * List<Object> result = (List<Object>) customerList; Iterator itr = 
     * result.iterator(); while(itr.hasNext()){ Object[] obj = (Object[]) 
     * itr.next(); 
     * 
     * System.out.println(String.valueOf(obj[0])+" "+String.valueOf(obj[1] 
     *)); 
     * 
     */ 

     /* 
     * for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread(obj 
     *); executor.execute(worker);//calling execute method of 
     * ExecutorService } 
     */ 
     /*executor.shutdown(); 
     while (!executor.isTerminated()) { 
     } 

     System.out.println("Finished all threads");*/ 
    } 
} 
} 

WorkerThread.java

package com.bcj.creditcardprocess.service; 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Random; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 

import com.bcj.creditcardprocess.dao.CreditCardDao; 
import com.bcj.creditcardprocess.model.CreditCard; 
import com.bcj.creditcardprocess.model.Customer; 

@Service 
public class WorkerThread implements Runnable { 

    @Autowired 
    private CreditCardDao cCardDao; 

    public void setcCardDao(CreditCardDao cCardDao) { 
     this.cCardDao = cCardDao; 
    } 

    public WorkerThread() { 

    } 

    WorkerThread(Customer cust2) { 
     this.cust = cust2; 
    } 

    Customer cust; 

    public void run() { 

     System.out.println(Thread.currentThread().getName() + " (Start) message = " + cust.getFirstName()); 

     try { 
      getCutomerDetailsByTextFile(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     System.out.println(Thread.currentThread().getName() + " (End)"); 

    } 

    public synchronized void getCutomerDetailsByTextFile() throws IOException { 

     FileReader fr = new FileReader("details.txt"); 
     BufferedReader br = new BufferedReader(fr); 

     String line = ""; 
     while ((line = br.readLine()) != null) { 
      System.out.println(line); 

      String[] details = line.split(" "); 

      if (details[0].equalsIgnoreCase(cust.getFirstName()) && details[1].equalsIgnoreCase(cust.getLastName()) 
        && details[2].equals(cust.getSsn())) { 
       System.out.println(" ssn had"); 

       if (Integer.parseInt(details[3]) > 700 && Integer.parseInt(cust.getAnnualIncome()) > 100000) { 

        CreditCard card = new CreditCard(); 
        card.setCreditLimit(5000); 
        card.setCustomerId(cust.getId()); 
        generateCardNumber(card, cust); 

        cust.setStatus("Approved"); 

       } else if (Integer.parseInt(details[3]) > 600 && Integer.parseInt(details[3]) < 700 
         && Integer.parseInt(cust.getAnnualIncome()) > 70000) { 

        CreditCard card = new CreditCard(); 
        card.setCreditLimit(3000); 
        card.setCustomerId(cust.getId()); 
        generateCardNumber(card, cust); 

        cust.setStatus("Approved"); 

       } else { 
        cCardDao.updateCustomer(cust); 

        cust.setStatus("Declined"); 
       } 

       break; 

      } 
     } 

    } 

    public void threadmain(List<Customer> customerList) { 

     ExecutorService executor = Executors.newFixedThreadPool(5); 

     for (Iterator iterator = customerList.iterator(); iterator.hasNext();) { 
      Customer cust = (Customer) iterator.next(); 

      Runnable worker = new WorkerThread(cust); 
      executor.execute(worker);// calling execute method of 
             // ExecutorService 
     } 
     executor.shutdown(); 
     while (!executor.isTerminated()) { 
     } 

     System.out.println("Finished all threads"); 

    } 

    private void generateCardNumber(CreditCard cCard, Customer cust) { 

     Random rand = new Random(); 

     String cardNumber = Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000) 
       + Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000); 

     String cvv = Integer.toString(rand.nextInt(999) + 100); 

     Calendar cal = Calendar.getInstance(); 
     Date today = cal.getTime(); 
     cal.add(Calendar.YEAR, 3); // to get previous year add -1 
     Date next = cal.getTime(); 

     SimpleDateFormat adf = new SimpleDateFormat("MM/YY"); 
     String expiryDate = adf.format(next); 

     cCard.setCardNumber(cardNumber); 
     cCard.setCvv(cvv); 
     cCard.setExpiryDate(expiryDate); 

     cCardDao.persistCreditCard(cCard, cust);  
    }  
} 

CreditCardDao.java

package com.bcj.creditcardprocess.dao; 

import java.util.List; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 
import com.bcj.creditcardprocess.model.CreditCard; 
import com.bcj.creditcardprocess.model.Customer; 

@Repository 
@Transactional 
public class CreditCardDao { 

    @Autowired 
    private SessionFactory sessionFactory; 
    private Session session = sessionFactory.getCurrentSession(); 

    public SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 

    // Session session = sessionFactory.getCurrentSession(); 
    List<Customer> custs; 

    public List<Customer> getCustomerList() { 

     Transaction tx = session.beginTransaction(); 
     List custs = session.createQuery("FROM Customer WHERE status='New'").list(); 

     return custs;  
    } 

    public void persistCreditCard(CreditCard cCard, Customer cust) { 
     int x = cCard.getCustomerId(); 
     Session session = sessionFactory.getCurrentSession(); 
     Transaction tx = session.beginTransaction(); 
     session.persist(cCard); 
     session.update(cust); 

     System.out.println("customer saved sucessfully" + cCard);  
    } 

    public void updateCustomer(Customer cust) { 
     Session session = sessionFactory.getCurrentSession(); 
     Transaction tx = session.beginTransaction(); 
     session.update(cust);  
    }  
} 

Spring.xml

<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.0.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 

    <mvc:annotation-driven /> 
    <context:component-scan base-package="com.bcj.creditcardprocess" /> 

    <bean 
     class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="prefix" value="/views/" /> 
     <property name="suffix" value=".jsp" /> 
    </bean> 

    <bean id="cCardService" class="com.bcj.creditcardprocess.service.CreditCardService" /> 
    <bean id="cCardDao" class="com.bcj.creditcardprocess.dao.CreditCardDao" /> 

    <tx:annotation-driven transaction-manager="transactionManager" /> 

    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory" /> 
    </bean> 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/citibank" /> 
     <property name="username" value="root" /> 
     <property name="password" value="root" /> 
    </bean> 

    <!--Hibernate 4 SessionFactory Bean definition --> 
    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="annotatedClasses"> 
      <list> 
       <value>com.bcj.creditcardprocess.model.CreditCard</value> 
       <value>com.bcj.creditcardprocess.model.Customer</value> 
      </list> 
     </property> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect 
       </prop> 
       <prop key="hibernate.hbm2ddl.auto">update 
       </prop> 
       <prop key="hibernate.show_sql">true</prop> 
       <!-- <prop key="hibernate.current_session_context_class">thread</prop> --> 
      </props> 
     </property> 
    </bean> 
</beans> 

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>com.bcj</groupId> 
    <artifactId>creditcardprocess</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <name>creditcardprocess</name> 
    <url>http://maven.apache.org</url> 

    <properties> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    </properties> 

    <dependencies> 
    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>3.8.1</version> 
     <scope>test</scope> 
    </dependency> 

<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-tx</artifactId> 
    <version>4.3.7.RELEASE</version> 
</dependency> 


    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> 
<dependency> 
    <groupId>org.hibernate</groupId> 
    <artifactId>hibernate-core</artifactId> 
    <version>4.3.3.Final</version> 
</dependency> 
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> 



    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-context</artifactId> 
     <version>4.3.7.RELEASE</version> 
    </dependency> 
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java--> 
<dependency> 
    <groupId>mysql</groupId> 
    <artifactId>mysql-connector-java</artifactId> 
    <version>6.0.6</version> 
</dependency> 


    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-core</artifactId> 
     <version>4.3.7.RELEASE</version> 
    </dependency> 
    <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> 
<dependency> 
    <groupId>commons-dbcp</groupId> 
    <artifactId>commons-dbcp</artifactId> 
    <version>1.4</version> 
</dependency> 


    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-webmvc</artifactId> 
     <version>4.3.7.RELEASE</version> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-web</artifactId> 
     <version>4.3.7.RELEASE</version> 
    </dependency> 
    <dependency> 
     <groupId>javax.servlet</groupId> 
     <artifactId>servlet-api</artifactId> 
     <version>2.5</version> 
    </dependency> 

    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-orm</artifactId> 
     <version>4.3.7.RELEASE</version> 
    </dependency> 
    </dependencies> 
</project> 
+0

dao,服務或控制器以及配置的代碼都不錯。 –

+0

代碼格式 – bc004346

+0

這不是[最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)。請考慮發佈完整的,相關的代碼** ** – bc004346

回答

0

也許嘗試改變

private Session session = sessionFactory.getCurrentSession(); 

的功能

public Session getSession() { 
    return sessionFactory.getCurrentSession(); 
} 

我的類初始化過程中的思維,類試圖初始化公開會議會議。而sessionFactory還沒有準備好。

0

getSessionFactory()CreditCardDao.java被扔nullPointerException,因爲你還沒有初始化的SessionFactory所以它的initialy指向null。 你會是這樣做的:

private SessionFactory sessionFactory=//build sessionfactory code

注意,SessionFactory應創建只有一次,你可以使用該singleton設計模式。

+0

intially spring會注入sessionfactory嗎? 但在接下來的方法,即persistcreditcard()和updatecustomer()我通過sessionFactory創建會話。所以在這個方法會話是空的,但在第一getcustomers()我能夠得到客戶。 –

+0

我看到你正在使用爲你注入配置的@Autowired註釋,看到這個線程可能會幫助你調試問題:http://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage –

相關問題