0

我创建了一个 DAO (ForecastPersistorDao.java),它是接口及其对应的实现 (ForecastPersistorDaoImpl.java)。该实现有一个方法“persist()”,其工作是将一些数据持久保存到数据库中。当我尝试调用 persist 来持久化数据时,它会抛出 NullPointerException,因为它没有正确初始化 SessionFactory。请帮我指出我可能做错了什么:

ForecastPersistorDao.java

public interface ForecastPersistorDao {

    void persist(List<ForecastedDemand> forecastedDemands);
    List<DemandForecast> retrieveLastForecast(String marketplaceId);

}

ForecastPersistorDaoImpl.java

@Repository("forecastPersistorDao")
public class ForecastPersistorDaoImpl implements ForecastPersistorDao {

    private SessionFactory sessionFactory;

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

    /**
     * Persist forecast in the database for later
     * 
     * @param forecastedDemands
     *            List of forecast for all asin:marketplaceId tuple
     */
    @Transactional
    @Override
    public void persist(List<ForecastedDemand> forecastedDemands) {
        System.out.println("THIS IS ALWAYS NULL-------->>>>>>>> " + sessionFactory);
        Session session = sessionFactory.getCurrentSession();
        Date forecastCalculationDate = new Date();

        // For each [asin:marketplace] tuple
        for (ForecastedDemand forecastedDemand : forecastedDemands) {
            String asin = forecastedDemand.getAsinMarketplaceId().getAsin();
            String marketplaceId = forecastedDemand.getAsinMarketplaceId().getMarketplaceId();
            String forecastingModel = forecastedDemand.getForecastingModel();
            SortedMap<Instant, Double> forecast = forecastedDemand.getForecast();

            // for each forecast date - write an entry in demand_forecasts table
            for (Map.Entry<Instant, Double> entry : forecast.entrySet()) {
                Date dateOfForecast = entry.getKey().toDate();
                double quantityForecasted = entry.getValue();
                DemandForecast forecastToPersist = new DemandForecast(asin, marketplaceId, forecastCalculationDate,
                        forecastingModel, quantityForecasted, dateOfForecast);
                session.save(forecastToPersist);
            }
        }
    }

主类(Runner.java):

public final class FbsRunner {
    private ForecastPersistorDao forecastPersistorDao;

    public static void main(String[] args) {
        Runner runner = new Runner();
        runner.run();
    }

    public void run() {
        ApplicationContext context =
                new FileSystemXmlApplicationContext("spring-configuration/application-config.xml");
        forecastPersistorDao = (ForecastPersistorDao) context.getBean("forecastPersistorDao"); // this works fine

        System.out.println(">>>>>>>>>> forecastPersistorDao [this is fine (not null)]: " + forecastPersistorDao);

        List<ForecastedDemand> forecastedDemand = [a list of Forecasted demand to be persisted int he DB]
        // THE CALL BELOW FAILS...
        forecastPersistorDao.persist(forecastedDemands);
        System.out.println("Persisted demand in the database"); // We don't reach here.
    }
}

弹簧配置/应用程序配置.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    ">

    <!--  The main application context spring configuration -->
    <import resource="application/hibernate.xml" />
    <import resource="common/hibernate.xml" />

    <!--<import resource="application/proxies.xml" />-->
    <!--<import resource="common/aggregators.xml" /> -->
    <import resource="application/environment.xml" />
    <!--
        Add any beans specific to your application here
    -->
    <bean id="forecastPersistorDao" class="com.amazon.fresh.fbs.dao.ForecastPersistorDaoImpl" />

</beans>

应用程序/hibernate.xml:

<bean id="SessionFactory"
          class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
          parent="AbstractSessionFactory" depends-on="EnvironmentHelper" >
        <property name="hibernateProperties">
...
...
everything as expected
...
</bean>

常见/hibernate.xml:

<beans ... >
bean id="AbstractSessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
            abstract="true">
        <property name="mappingResources">
            <list>
                <value>com/amazon/fresh/fbs/dao/hibernate/RtipData.hbm.xml</value>
                <value>com/amazon/fresh/fbs/dao/hibernate/Vendor.hbm.xml</value>
                <value>com/amazon/fresh/fbs/dao/hibernate/AdjustmentPeriod.hbm.xml</value>
                <value>com/amazon/fresh/fbs/dao/hibernate/DemandForecast.hbm.xml</value>
            </list>
        </property>
        <property name="exposeTransactionAwareSessionFactory">
            <value>true</value>
        </property>
     </bean>

     <!-- Use Spring transactions for Hibernate -->
     <tx:annotation-driven transaction-manager="txManager" mode='proxy' proxy-target-class='true'/> 

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

     <aop:aspectj-autoproxy/>
</beans>
4

2 回答 2

1

请尝试添加<context:component-scan base-package="YOUR PACKAGE NAME" />到您的application-config.xml. 这将告诉 Spring 扫描将自动注册为 Spring bean 的注释组件。

“YOUR PACKAGE NAME”应该是用于扫描带注释组件的包名称。

于 2013-08-28T02:49:26.823 回答
1

sessionFactory 没有正确自动装配,为 ForecastPersistorDaoImpl 添加“@component”并在 application-config.xml 中添加“context:component-scan”以告诉 spring 初始化。

于 2013-08-28T05:03:21.340 回答