2013-10-08 1 views
0

내 구성에 문제가 있습니다. 여기에 문제가 있습니다. 그 같은 세션을 열 ICAN :봄 + 최대 절전 모드 4 + Junit 4 자동 무선 세션을 열 수 없습니다.

@Test 
    public void testSessionFactory() 
    { 
     try { 
      Configuration configuration = new Configuration() 
      .addClass(com.mcfly.songme.pojo.Sysparameters.class) 
      .configure(); 
      ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration 
        .getProperties()); 

      SessionFactory sessionFactory = configuration 
        .buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry()); 
      System.out.println("test"); 
      Session session = sessionFactory.openSession(); 
      System.out.println("Test connection with the database created successfuly."); 
     }catch (Throwable ex) { 
      ex.printStackTrace(); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 

을하지만 난 세션이 openned 결코 그렇게 할 경우 :

@Test 
public void testFindAll() 
{ 
    try { 
     List<Sysparameters> sys = null; 
     System.out.println("test"); 
     SysparametersDAO sysDao = new SysparametersDAO(); 
     System.out.println("test"); 
     sys = sysDao.findAll(); 
     System.out.println(sys.size()); 
    } catch (Throwable ex) { 
     ex.printStackTrace(); 
     throw new ExceptionInInitializerError(ex); 
    } 
} 

내의 configuration.xml :

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

    <context:annotation-config/> 

    <context:component-scan base-package="com.mcfly.songme.pojo" /> 


    <!-- JDBC data source --> 
<!--  <bean id="myDataSource" class="org.springframework.jdb.datasource.DriverManagerDataSource"> --> 
    <bean id="myDataSource" 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/songme"/> 
     <property name="maxActive" value="10"/> 
     <property name="minIdle" value="5"/> 
     <property name="username" value="root"/> 
     <property name="password" value="root"/> 
     <property name="validationQuery" value="SELECT 1"/> 
    </bean> 

    <!-- hibernate session factory --> 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="myDataSource"/> 
     <property name="packagesToScan" value="com.mcfly.songme.pojo"/> 
     <property name="configLocation" value="classpath:com/mcfly/songme/pojo/hibernate.cfg.xml" /> 
    </bean> 

    <!-- Hibernate transaction Manager --> 
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory"/> 
    </bean> 

    <!--  Activates annotation based transaction management --> 
    <tx:annotation-driven transaction-manager="transactionManager"/> 


</beans> 

내 DAO 파일 :

package com.mcfly.songme.pojo; 

import java.io.File; 
import java.util.List; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.stereotype.Component; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 

@Repository 
@Component 
public class SysparametersDAO 
{ 
    @Autowired(required=true) 
    @Qualifier("sessionFactory") 
    private SessionFactory sessionFactory; 

    private Session session = sessionFactory.getCurrentSession(); 


    @Transactional 
    public List<Sysparameters> findAll() 
    { 
     try { 
      if(getSessionFactory()==null) { 
       System.out.println("NULL SESSION FACTORY"); 
      } 
      session = getSessionFactory().getCurrentSession(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     @SuppressWarnings("unchecked") 
     List<Sysparameters> sys = (List<Sysparameters>) session.createQuery("from sysparameters").list(); 
     return sys; 
    } 

    public SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

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

} 

내 en tity 파일 :

package com.mcfly.songme.pojo; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 

// Generated 8 oct. 2013 16:31:22 by Hibernate Tools 4.0.0 

/** 
* Sysparameters generated by hbm2java 
*/ 
@Entity 
@Table(name = "sysparameters") 
public class Sysparameters implements java.io.Serializable { 

    @Id 
    private Integer id; 
    @Column(name = "name") 
    private String name; 
    @Column(name = "value") 
    private String value; 

    public Sysparameters() { 
    } 

    public Sysparameters(String name, String value) { 
     this.name = name; 
     this.value = value; 
    } 

    public Integer getId() { 
     return this.id; 
    } 

    public void setId(Integer id) { 
     this.id = id; 
    } 

    public String getName() { 
     return this.name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getValue() { 
     return this.value; 
    } 

    public void setValue(String value) { 
     this.value = value; 
    } 

} 

내 테스트 파일 구성 :

package com.mcfly.songme.pojo.test; 

@ContextConfiguration("classpath:/files-servlet.xml") 
@RunWith(SpringJUnit4ClassRunner.class) 
public class SysparameterPOJOTest 
{ 

난 정말 내가 뭘 잘못 이해할 수 없습니다. 아이디어가 있다면 Thx에게 도움을 요청하십시오. 당신은 내가 객체에서 세션을 얻을 tryed 말했듯이


아직도 그 코드로 널 세션 공장

oct. 09, 2013 11:38:06 AM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet 
INFO: Using DataSource [[email protected]] of Hibernate SessionFactory for HibernateTransactionManager 
java.lang.NullPointerException 
    at com.mcfly.songme.pojo.test.SysparameterPOJOTest.testFindAll_(SysparameterPOJOTest.java:81) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) 

을 가진

@Test 
    public void testFindAll_() 
    { 
     Session session = null; 
     try { 
      Sysparameters sys = null; 
      SysparametersDAO sysDAO = new SysparametersDAO(); 
      session = sysDAO.getSessionFactory().getCurrentSession(); 
//   sys = new SysparametersHome().findById(1); 
     } catch (Throwable ex) { 
      ex.printStackTrace(); 
      throw new ExceptionInInitializerError(ex); 
     } finally { 
      Assert.assertNotNull(session); 
     } 
    } 

그래서 내 세션 공장 것 같다 아직 null :/

+0

나는이 예외가 있어요 \ 작업 \ WebTest에 \ songMe \ 구축 \ classes \ com \ mcfly \ songme \ pojo \ SysparametersDAO.class] : 빈 인스턴스화에 실패했습니다. 중첩 예외는 org.springframework.beans.BeanInstantiationException : 빈 클래스 [com.mcfly.songme.pojo.SysparametersDAO]를 생성 할 수 없습니다 : 생성자가 예외를 throw했습니다. 중첩 예외는 java.lang.NullPointerException입니다. – McflyDroid

+0

질문을 편집하여 추가 정보를 추가 할 수 있습니다. 코멘트에 넣지 마십시오. 또한,'files-servlet.xml'은 위에 올려 놓은 configuration.xml과 같은 파일입니까? –

답변

0

첫 번째 문제는

입니다.
@Autowired(required=true) 
@Qualifier("sessionFactory") 
private SessionFactory sessionFactory; 

private Session session = sessionFactory.getCurrentSession(); 

스프링 자동 와이어 링은 두 단계로 진행됩니다. 먼저 bean이 인스턴스화되고 (이 경우 기본 생성자가 호출 됨) 리플렉션을 사용하여 필드가 설정됩니다. 위의 경우 개체가 만들어지면 필드도 기본적으로 null으로 초기화됩니다. 그래서

private Session session = sessionFactory.getCurrentSession(); 

그것이 null 기준에 getCurrentSession() 호출하는 Session를 얻을 수하려고 할 때.

Session 개체를 인스턴스 수준에서 가져 오면 안됩니다. 당신은 각각의 개별 메소드 호출 안에 그것을 가져와야합니다. org.springframework.beans.factory.BeanCreationException :에 의한 : 오류는 이름을 가진 콩을 만드는 'sysparametersDAO'파일 [에 정의 된 C :

관련 문제