0

I just wrote a simple test with spring+hibernate, but I'm getting a null pointer exception in this test as sessionFactory is always null. Then I tried to invoke the method getBean() to get sessionFactory. I found that it works, but @autowired doesn't. Why?

private ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
protected SessionFactory sessionFactory=(SessionFactory)applicationContext.getBean("sessionFactory");

Any help is appreciated; thanks.

Below is the content of relevant files:

Here is my applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans         
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        
  http://www.springframework.org/schema/aop         
  http://www.springframework.org/schema/aop/spring-aop-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
  http://www.springframework.org/schema/cache 
  http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
<!-- <bean id="..." class="..."> collaborators and configuration for this 
    bean go here </bean> <bean id="..." class="..."> collaborators and configuration 
    for this bean go here </bean> more bean definitions go here -->

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url"
        value="jdbc:mysql://localhost:3306/desserthouse?autoReconnect=true" />
    <property name="username" value="root" />
    <property name="password" value="1234" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="edu.nju.dessertHouse.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.connection.autocommit">true</prop>
        </props>
    </property>

</bean>

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

<bean id="autowiredAnnotationBeanPostProcessor"
    class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="edu.nju.dessertHouse" />
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*User" propagation="REQUIRED" />
        <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut id="serviceOperation"
        expression="execution( * edu.nju.dessertHouse.service..*Service.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>

Here is my test MemberDaoImpl:

@Repository
public class MemberDaoImpl implements MemberDao {

@Autowired
protected SessionFactory sessionFactory;

protected Session session;


protected static MemberDaoImpl memberDao=new MemberDaoImpl();

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

@Override
public void resigter(Member member) {
    try {  
        session=getSession();
        Transaction tx=session.beginTransaction();
        session.save(member);
        tx.commit();
        session.close();
        sessionFactory.close();
        System.out.println("ok");
    }  
    catch (Exception e) {  
        e.printStackTrace();
    }   
}

public static void main(String[] args){
    Member member=new Member();
    member.setMemberid(1);
    member.setCreditCard("1");
    member.setMemberCard("1");
    member.setLocation("1");
    member.setMname("1");
    member.setPassword("1");
    member.setSex("1");
    member.setPoint(1);
    Calendar calendar=Calendar.getInstance();
    calendar.set(Calendar.YEAR,1995);
    calendar.set(Calendar.MONTH,7-1);  
    calendar.set(Calendar.DAY_OF_MONTH,6);
    Date date=new Date(calendar.getTimeInMillis());
    member.setBirthday(date);
    memberDao.resigter(member);

}

}

Why is sessionFactory null? I have tried many methods, but it still doesn't work.

helencrump
  • 1,351
  • 1
  • 18
  • 27
Song
  • 23
  • 1
  • 4
  • Possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – kryger Feb 16 '16 at 16:58

1 Answers1

0

You are creating a new instance of MemberDAOImpl by doing this:

protected static MemberDaoImpl memberDao=new MemberDaoImpl();

And then you are invoking register() on this new instance by doing memberDao.resigter(member);.

How do you think the Spring Framework works?

You should not make a new instance of MemberDAOImpl and just do register(member); instead of memberDao.resigter(member); as you have already created a singleton MemberDAOImpl by annotating it with @Repository. This has the SessionFactory Bean injected into it.

user2004685
  • 9,548
  • 5
  • 37
  • 54