Spring TransactionProxyFactoryBean没有为服务加载dao

时间:2012-11-12 09:40:57

标签: java spring hibernate gwt dao

我在使用GWT框架下的Hibernate设置Spring时遇到了麻烦。我对GWT很新。我有应用程序上下文设置和加载没有输出错误,但我目前的主要问题是我的服务层实现(PobaseServiceImpl)需要我在appcontext中设置的DAO,但它没有包装DAO。当然,我的RPC试图调用dao方法导致NullPointerException。当我初始化它时,不会由TransactionProxyFactoryBean设置pobaseDao。

总结: DAO应该由我的其他服务创建(即配置为)Spring。然后通过Spring注入服务。然后使用DAO将其包装在Spring事务代理(org.springframework.transaction.interceptor.TransactionProxyFactoryBean)中,并为其提供一个Hibernate SessionFactory(org.springframework.orm.hibernate4.LocalSessionFactoryBean)。但由于某种原因,它没有设置dao

所以我的应用程序上下文是通过ServletContextListener加载的。 这是我的应用程序上下文:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

  <!--
    Spring Framework application context definition for the POBASE Website.
  -->

<beans>

  <!-- Configurer that replaces ${...} placeholders with values from a properties file -->
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
         <value>classpath:/pobase.properties</value>
         <value>file:${user.home}/pobase.properties</value>
      </list>
    </property>
    <property name="ignoreResourceNotFound" value="no"/>
  </bean>

  <!-- Hibernate Data Source -->
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${pobase.database.driver}" />
    <property name="url" value="${pobase.database.url}" />
    <property name="username" value="${pobase.database.user}" />
    <property name="password" value="${pobase.database.password}" />
  </bean>

  <!-- Hibernate SessionFactory -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource">
      <ref bean="dataSource" />
    </property>
    <property name="packagesToScan" value="nz.co.doltech.pobase.client.entity"/>
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">${pobase.hibernate.dialect}</prop>
        <prop key="hibernate.show_sql">${pobase.hibernate.show_sql}</prop>
        <prop key="javax.persistence.validation.mode">none</prop>
      </props>
    </property>
  </bean>

  <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>

  <!-- Default transaction proxy, defining the transactional behaviour for
    a typical Dao configuration -->
  <bean id="baseDaoTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
    abstract="true">
    <property name="transactionManager" ref="transactionManager" />
    <property name="transactionAttributes">
      <value>*=PROPAGATION_MANDATORY</value>
    </property>
  </bean>

  <!-- Default transaction proxy, defining the transactional behaviour for
    a typical Service configuration -->
  <bean id="baseServiceTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
    abstract="true">
    <property name="transactionManager" ref="transactionManager" />
    <property name="transactionAttributes">
      <value>*=PROPAGATION_REQUIRED</value>
    </property>
  </bean>

  <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

  <bean id="pobaseDao" parent="baseDaoTransactionProxy">
    <property name="target" ref="pobaseDaoTarget" />
  </bean>
  <bean id="pobaseDaoTarget" class="nz.co.doltech.pobase.server.dao.PobaseHibernateDao">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>

  <bean id="pobaseService" parent="baseServiceTransactionProxy">
    <property name="target" ref="pobaseServiceTarget" />
  </bean>
  <bean id="pobaseServiceTarget" class="nz.co.doltech.pobase.server.service.PobaseServiceImpl">
    <property name="pobaseDao" ref="pobaseDao" />
    <!-- property name="accessControlService" ref="accessControlService" />
    <property name="lookupService" ref="lookupService"/>
    <property name="notificationService" ref="notificationService"/ -->
  </bean>

</beans>

这是我的RPC servlet实现:

package nz.co.doltech.pobase.server.service;

/**
 * Extends RSS and implements the PobaseService
 * @author Ben
 */
@SuppressWarnings("serial")
public class PobaseServiceImpl extends RemoteServiceServlet implements PobaseService {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(PobaseServiceImpl.class.getName());

    private PobaseDao pobaseDao;
    private final HashMap<Integer, PobaseEntity> pobaseEntities = new HashMap<Integer, PobaseEntity>();

    private void fetchExternPobase()
    {
        pobaseEntities.clear();
        List<PobaseEntity> pobaseList = pobaseDao.getAllPobase();
        for (int i = 0; i < pobaseList.size(); i++)
        {
            PobaseEntity en = pobaseList.get(i);
            if(en != null) {
                pobaseEntities.put(en.getId(), en);
            }
        }
    }

    public void setPobaseDao(PobaseDao dao)
    {
        this.pobaseDao = dao;
    }

    public PobaseDao getPobaseDao()
    {
        return this.pobaseDao;
    }

    public PobaseData addLocalPobase(PobaseData pobase)
    {
        PobaseEntity entity = new PobaseEntity();
        entity.mirrorObjectData(pobase);

        pobase.setId(pobaseEntities.size());
        pobaseEntities.put(pobase.getId(), entity); 

        return entity.getDataObject();
    }

    public PobaseData updateLocalPobase(PobaseData pobase)
    {
        PobaseEntity entity = new PobaseEntity();
        entity.mirrorObjectData(pobase);

        pobaseEntities.remove(entity.getId());
        pobaseEntities.put(entity.getId(), entity);

        return entity.getDataObject();
    }

    public Boolean deleteLocalPobase(int id)
    {
        pobaseEntities.remove(id);
        return true;
    }

    public ArrayList<PobaseData> deleteLocalPobases(ArrayList<Integer> ids)
    {
        for (int i = 0; i < ids.size(); ++i) {
            deleteLocalPobase(ids.get(i));
        }

        return getLocalPobaseData();
    }

    public ArrayList<PobaseData> getLocalPobaseData()
    {
        ArrayList<PobaseData> pobaseList = new ArrayList<PobaseData>();
        Iterator<Integer> it = pobaseEntities.keySet().iterator();
        while(it.hasNext())
        {
            PobaseData pobase = pobaseEntities.get(it.next()).getDataObject();
            pobaseList.add(pobase);
        }
        return pobaseList;
    }

    public PobaseData getLocalPobase(int id)
    {
        return pobaseEntities.get(id).getDataObject();
    }

    public ArrayList<PobaseData> resyncExternPobase()
    {
        fetchExternPobase();
        return getLocalPobaseData();
    }

}

此处还有Web应用程序的启动日志:

ServletContextListener started
Nov 12, 2012 8:20:33 PM nz.co.doltech.pobase.SpringInitialiser initSpringContext
INFO: Creating new Spring context. Configs are [/nz/co/doltech/pobase/appcontext.xml]
Nov 12, 2012 8:20:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@8423321: startup date [Mon Nov 12 20:20:33 NZDT 2012]; root of context hierarchy
Nov 12, 2012 8:20:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [nz/co/doltech/pobase/appcontext.xml]
Nov 12, 2012 8:20:33 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [pobase.properties]
Nov 12, 2012 8:20:33 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from URL [file:/home/ben/pobase.properties]
Nov 12, 2012 8:20:33 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4c56666d: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,transactionManager,baseDaoTransactionProxy,baseServiceTransactionProxy,pobaseDao,pobaseDaoTarget,pobaseService,pobaseServiceTarget]; root of factory hierarchy
Nov 12, 2012 8:20:33 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.postgresql.Driver
Nov 12, 2012 8:20:33 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Nov 12, 2012 8:20:33 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.7.Final}
Nov 12, 2012 8:20:33 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 12, 2012 8:20:33 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Nov 12, 2012 8:20:34 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Nov 12, 2012 8:20:34 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Nov 12, 2012 8:20:34 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Nov 12, 2012 8:20:34 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Nov 12, 2012 8:20:34 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@55acc0d4] of Hibernate SessionFactory for HibernateTransactionManager
Starting Jetty on port 8888

任何人都有任何想法,为什么它不工作?这里的一些规格:

  • Spring 3.2.0
  • Hibernate4
  • GWT SDK 2.4.0

感谢我能得到的任何帮助!

干杯, 本

1 个答案:

答案 0 :(得分:1)

您的PobaseServiceImpl类不是线程安全的。 在Java中,任何远程调用服务(当然,容器中的单例也是如此)应该准备好从不同的线程调用其方法,并且可以在不同的线程中同时执行相同的方法。

整个班级需要详细检查。

首先,您应该使用ConcurrentHashMap而不是HashMap。并且需要仔细重写所有方法 - 例如返回ArrayList的方法 (public ArrayList<PobaseData> resyncExternPobase()) 应该制作数据的防御性副本。

作为替代方案,您应该考虑使公共方法成为您的服务方法同步,但这会强制方法按顺序执行,如果预计服务会被积极使用,则会破坏性能来自不同的主题。

作为参考,请考虑阅读Brian Goetz Java Concurrency In Practice,第5章。构建块,尤其是 5.1同步集合 5.2。并发馆藏

更新:您的 PobaseServiceImpl 似乎是一个由servlet容器实例化的servlet - 用Spring bean填充其字段你应该使用Spring实用程序方法 - 例如WebApplicationContextUtils - 互联网上有很多例子,例如http://pgt.de/2009/07/17/non-invasive-gwt-and-spring-integration-reloaded/