1

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

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

所以我的应用程序上下文是通过 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

任何人都知道为什么它不起作用?这里的一些规格:

  • 春天 3.2.0
  • 休眠4
  • GWT SDK 2.4.0

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

干杯,本

4

1 回答 1

1

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

整个班级都需要详细检查。

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

作为替代方案,您应该考虑将公共方法设置为您的服务方法同步,但是,这将强制方法按顺序执行,并且如果期望从不同线程主动使用服务,则会降低性能。

作为参考,请考虑阅读 Brian Goetz Java Concurrency In Practice,第 5 章。Building Blocks,尤其是5.1 Synchronized collections5.2。并发集合

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

于 2012-11-12T10:43:16.633 回答