当前位置: 首页 > 面试题库 >

使用Spring依赖注入时,Hibernate SessionFactory始终为null

唐俊爽
2023-03-14
问题内容

我在中得到了NullpointerException我的保存方法CityDaoImpl。似乎sessionFactory没有自动接线,因为在调试时发现从未注入sessionFactory
CityDaoImpl。我浏览了许多答案,但没有一个可以解决我的问题。这是我的HibernateConfig.xml文件:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan 
        base-package="com.testing" />
    <context:annotation-config></context:annotation-config>
    <tx:annotation-driven/>
    <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/sybrium" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="annotatedClasses">
            <list>
                <value>com.testing.bean.City</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="debug">true</prop>
            </props>
        </property>
    </bean>
    <bean id="cityDao" class="com.testing.dao.CityDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>

这是CityDaoImpl.java

public class CityDaoImpl implements CityDao{

    @Autowired
    private SessionFactory sessionFactory;

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

    public void save(City city){
        this.sessionFactory.getCurrentSession().save(city);
    }

}

现在,我正在对dao类进行单元测试。但是NPE失败了。

public class TestCityDao {

    ApplicationContext ctx;

    @Before
    public void setup(){
        ctx = new ClassPathXmlApplicationContext("HibernateConfig.xml");
    }

    @Test
    public void test(){
        City city = new City();
        city.setName("Karachi");
        city.setCountry("Pakistan");
        CityDao dao = (CityDao) ctx.getBean("cityDao");
        dao.save(city);
    }
}

控制台输出:

Jan 15, 2015 11:54:53 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@b34bf3: display name [org.springframework.context.support.ClassPathXmlApplicationContext@b34bf3]; startup date [Thu Jan 15 23:54:53 PKT 2015]; root of context hierarchy
Jan 15, 2015 11:54:53 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [HibernateConfig.xml]
Jan 15, 2015 11:54:53 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@b34bf3]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1b8202e
Jan 15, 2015 11:54:53 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1b8202e: defining beans [dataSource,sessionFactory,cityDao]; root of factory hierarchy
Jan 15, 2015 11:54:53 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jan 15, 2015 11:54:53 PM org.springframework.orm.hibernate3.LocalSessionFactoryBean buildSessionFactory
INFO: Building new Hibernate SessionFactory

抛出的异常是:

java.lang.NullPointerException
    at com.testing.dao.CityDaoImpl.save(CityDaoImpl.java:19)
    at com.testing.TestCityDao.test(TestCityDao.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

问题答案:

您声明sessionFactory依赖项:

<bean id="cityDao" class="com.testing.dao.CityDaoImpl">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

然后您还有:

@Autowired
private SessionFactory sessionFactory;

尝试删除@Autowired注释,因为如果使用XML配置,则多余。

仅仅因为添加了sessionFactory,并不意味着Spring也可以自动管理Hibernate Sessions。

您还需要添加:

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

以及:

<tx:annotation-driven/>

现在,你还需要添加@Transactional到您的 保存 例行:

@Transactional
public void save(City city){
    this.sessionFactory.getCurrentSession().save(city);
}


 类似资料:
  • 问题内容: Spring在以下方面很好地支持JUnit:使用和注释,事情看起来非常直观 该测试将能够在Eclipse&Maven中正确运行。我想知道TestNG是否有类似的东西。我正在考虑迁移到“下一代”框架,但没有找到与Spring测试匹配的对象。 问题答案: 它也可以与TestNG一起使用。

  • 在下面这样一个简单的测试类中: AddressInfoLocalizer(很抱歉这个奇怪的名字,但我不得不虚构)基本上是这样的: 当调用(在测试中)addressInfoLocalizer时,我不断得到一个NullPointerException。本地化(ip) , 在调试时,我实际上可以看到addressInfoLocalizer对象是null。 我用同样的方法创建了其他类,但只有这个类似乎有这

  • 我不太明白它解决了什么问题。它看起来像是这样说:“Hi.当你运行到这个函数时,返回一个对象,它是这种类型的,并且使用这些参数/数据。” 但是...我为什么要用这个?注我也从来不需要使用,但我理解这是为了什么。 在构建一个网站或桌面应用程序时,有哪些实际情况可以使用DI?我可以很容易地想出为什么有人想在游戏中使用接口/虚拟函数的例子,但是在非游戏代码中使用这种方法是极其罕见的(非常罕见,以至于我都记

  • 我遇到了依赖注入周期问题。我请求重新设计建议。提前谢谢。 错误描述:应用程序上下文中某些bean的依赖关系形成一个循环: 这是两个班 第一类: 第二类:

  • 使用 Jersey Spring DI,需要添加 jersey-spring3 模块 <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-spring3</artifactId> <version>2.15</version> </dependency> 上述模块不添加任何传

  • 我必须使用Spring Quartz和JDBC Store来调度应用程序。我不确定当从数据库触发作业时如何处理依赖注入。一种方法是在作业触发后从上下文中检索bean。但不会再有了。当在JDBC Store上使用Spring Quartz进行集群时,关于如何处理DI的任何想法。