2013-04-24 2 views
1

.getCurrentSession()으로 Session을 가져올 때 다음 오류가 발생합니다.최대 절전 모드 Spring에서 .getCurrentSession() 이후 오류

오류 :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.service.StudentService miniVLE.controller.miniVLEController.studentService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.dao.MiniVLEDAOImplementation miniVLE.service.StudentService.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEDAOImplementation' defined in file [C:\Users\1\Documents\NetBeansProjects\com3014_mini_VLE\build\web\WEB-INF\classes\miniVLE\dao\MiniVLEDAOImplementation.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [miniVLE.dao.MiniVLEDAOImplementation]: Constructor threw exception; nested exception is java.lang.NullPointerException

DAO 구현 :

import java.util.ArrayList; 
import java.util.List; 
import miniVLE.beans.Course; 
import miniVLE.beans.Department; 
import miniVLE.beans.Module; 
import miniVLE.beans.Student; 
import miniVLE.beans.TimeSlot; 
import org.hibernate.SessionFactory; 
import org.hibernate.criterion.Restrictions; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 

@Repository 
public class MiniVLEDAOImplementation implements MiniVLEDAO{ 

    // Used for communicating with the database 
    @Autowired 
    private SessionFactory sessionFactory; 

    /** 
    * DAO constructor filled with dummy data 
    */ 
    public MiniVLEDAOImplementation() { 
     System.out.println("*** MiniVLEDAOImplementation instantiated"); 
     Student s1 = new Student("123456","Bob","123"); 
     Department d1 = new Department("COM","Computing"); 
     Course c1 = new Course("COM3014","Web"); 
     c1.setDepartment(d1); 
     s1.setCourse(c1); 
     s1.setDept(d1); 

     // Add new student to the database 
     addStudentToDB(s1); 

    } 

    /** 
    * Gets the current session and adds new student row into the database 
    * @param student 
    */ 
    @Override 
    public void addStudentToDB(Student student) {   
     sessionFactory.getCurrentSession(); // here i got rid of full implementation as it fails on getting the current session 
    } ... 

디스패처 - 서블릿 :

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.0.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 

    <context:annotation-config /> 
    <context:component-scan base-package="miniVLE.controller" /> 
    <context:component-scan base-package="miniVLE.service" /> 
    <context:component-scan base-package="miniVLE.beans" /> 
    <context:component-scan base-package="miniVLE.dao" /> 

    <!-- Declare a view resolver--> 
    <bean id="viewResolver" 
      class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
      p:prefix="/WEB-INF/jsp/" 
      p:suffix=".jsp" /> 


    <!-- Connects to the database based on the jdbc properties information--> 
    <bean id="dataSource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name ="driverClassName" value="com.mysql.jdbc.Driver"/> 
     <property name ="url" value="jdbc:derby://localhost:1527/minivledb"/> 
     <property name ="username" value="root"/> 
     <property name ="password" value="123" /> 
    </bean> 

    <!-- Declares hibernate object --> 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect"> ${hibernate.dialect}</prop> 
       <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> 
      </props> 
     </property> 
     <!-- A list of all the annotated bean files, which are mapped with database tables--> 
     <property name="annotatedClasses"> 
      <list> 
       <value> miniVLE.beans.Course </value> 
       <value> miniVLE.beans.Student </value> 
       <value> miniVLE.beans.Department </value> 
       <value> miniVLE.beans.Module </value> 
       <value> miniVLE.beans.TimeSlot </value> 
      </list> 
     </property> 
    </bean> 

</beans> 
+0

생성자를 자동으로 생성하고 세션 팩토리를 생성자에 전달해야합니다. '@Autowired 공개 MiniVLEDAOI 구현 (SessionFactory sessionFactory) { \t this.sessionFactory = sessionFactory; \t // 귀하의 코드 } –

답변

3

빈을 생성하기 위해 Spring은 먼저 클래스의 '인수없는 생성자'를 사용하여 인스턴스를 만든 다음 리플렉션을 사용하여 @Autowired 필드를 자동 완성합니다.

하지만 생성자

public MiniVLEDAOImplementation() { 
    ... 
    // Add new student to the database 
    addStudentToDB(s1); 
} 

는 초기화되기 전에 SessionFactory를 사용하는 메소드를 호출합니다. 따라서 null이고 메소드를 호출 할 때 NullPointerException이 표시됩니다.

해당 시점부터 학생을 데이터베이스에 추가 할 수 없습니다. 수업을 테스트하려면 단위 테스트를 시도하십시오.

+1

@exomen 생성자에서 데이터베이스에 항목을 삽입하지 마십시오. 그건 아주 나쁜 습관입니다. –

+0

DAO가 초기화 된 후에 별도의 클래스에 추가하려고합니다. Sotirios Delimanolis 조언을 주셔서 감사합니다, 현재 나는 그것이 작동하는 방법을 undestand하려고 노력하고있어. – exomen

+0

@exmen 기꺼이 도와 드릴 수 있습니다. 나는 Spring이 모든 Spring 라이브러리에서 사용 되었기 때문에 Spring이 bean을 관리하고 autowiring을 수행하는 방법에 대해 읽는 것을 제안합니다. 그것은 장기적으로 도움이 될 것입니다. –