警告:上下文初始化期间遇到异常

时间:2017-04-14 16:48:06

标签: java spring hibernate

在它工作之前,但现在它不工作。以前当它工作时,我用来在CrediCarddao.java中获取会话Null,以更新客户状态并将新的信用卡记录插入数据库。

  

2017年4月14日上午9:32:36 org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh           信息:刷新org.springframework.context.support.FileSystemXmlApplicationContext@68de145:启动日期[Fri Apr 14 09: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]加载XML bean定义           2017年4月14日上午9:32:37 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache           信息:寻找@ControllerAdvice:org.springframework.context.support.FileSystemXmlApplicationContext@68de145:启动日期[Fri Apr 14 09:32:36 CDT 2017];上下文层次结构的根           2017年4月14日上午9:32:37 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache           信息:寻找@ControllerAdvice:org.springframework.context.support.FileSystemXmlApplicationContext@68de145:启动日期[Fri Apr 14 09:32:36 CDT 2017];上下文层次结构的根           2017年4月14日上午9:32:37 org.springframework.context.support.FileSystemXmlApplicationContext refresh           警告:在上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.BeanCreationException:创建名称为' creditCardDao'在文件[C:\ BCJ_DEC_2016 \ workspace \ CoreJava \ creditcardprocess \ target \ classes \ com \ bcj \ creditcardprocess \ dao \ CreditCardDao.class]中定义:bean的实例化失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[com.bcj.creditcardprocess.dao.CreditCardDao]:构造函数抛出异常;嵌套异常是java.lang.NullPointerException           线程" main"中的例外情况org.springframework.beans.factory.BeanCreationException:创建名称为' creditCardDao'的bean时出错。在文件[C:\ BCJ_DEC_2016 \ workspace \ CoreJava \ creditcardprocess \ target \ classes \ com \ bcj \ creditcardprocess \ dao \ CreditCardDao.class]中定义:bean的实例化失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[com.bcj.creditcardprocess.dao.CreditCardDao]:构造函数抛出异常;嵌套异常是java.lang.NullPointerException               在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)               在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)               在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)               在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)               at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:306)               在org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.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)               at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)               在org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)               在org.springframework.context.support.FileSystemXmlApplicationContext。(FileSystemXmlApplicationContext.java:140)               在org.springframework.context.support.FileSystemXmlApplicationContext。(FileSystemXmlApplicationContext.java:84)               在com.bcj.creditcardprocess.CreditCardMain.main(CreditCardMain.java:15)           引起:org.springframework.beans.BeanInstantiationException:无法实例化[com.bcj.creditcardprocess.dao.CreditCardDao]:构造函数抛出异常;嵌套异常是java.lang.NullPointerException               在org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)               在org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)               在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)               ......还有13个           引起:java.lang.NullPointerException               在com.bcj.creditcardprocess.dao.CreditCardDao。(CreditCardDao.java:22)               at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)               at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)               at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)               at java.lang.reflect.Constructor.newInstance(Constructor.java:423)               在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>

2 个答案:

答案 0 :(得分:0)

也许尝试改变

private Session session = sessionFactory.getCurrentSession();

到函数

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

我在类初始化期间,正在尝试初始化私有Session会话。而sessionFactory还没有准备好。

答案 1 :(得分:0)

CreditCardDao.java 中的getSessionFactory()正在抛出nullPointerException,因为您尚未初始化SessionFactory,因此它最初指向null 。 你会这样做:

private SessionFactory sessionFactory=//build sessionfactory code

请注意,SessionFactory只应创建一次,您可以使用singleton设计模式。