0

我们用 Java 在 mvc 中开发一个项目。我们想在我们的项目中添加一个 REST Web 服务,但是当我们想访问 DAO 层时,我们得到 sessionFactory is null 异常。我们如何通过 Web 服务注入 DAO?

你可以看到下面的代码

Web.java - 网络服务代码

package tr.com.server.webservice;

import java.util.ArrayList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import tr.com.server.model.Admin;
import tr.com.server.persistance.admin.AdminDAO;

@Path("/rota")
public class Web{
    @Autowired
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/add")
    @Transactional
    public String adminadd() throws Exception{

        Admin m = new Admin();
        m.setAdminname("John");
        m.setAdminpass("123456");
        AdminDAO a = new AdminDAO();
        a.add(m);

        return "added";
    }
}

AdminDAO.java - DAO 类

package tr.com.server.persistance.admin;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import tr.com.server.model.Admin;


@Repository
public class AdminDAO implements IAdminDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

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

    @Autowired
    @Transactional
    @Override
    public Admin add(Admin entity) throws Exception {
        try {

            getSessionFactory().getCurrentSession().save(entity);
            getSessionFactory().getCurrentSession().flush();
            getSessionFactory().getCurrentSession().refresh(entity);
            return entity;
        } catch (RuntimeException e) {

            throw new Exception(e);
        }
    }
}

iAdminDAO.java - AdminDAO 接口

package tr.com.server.persistance.admin;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import tr.com.server.model.Admin;

@Transactional
public interface IAdminDAO {

    Admin add(Admin entity) throws Exception;

}

/WEB-INF/xml/admin.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        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-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <bean id="iAdminBusinessManager" class="tr.com.server.business.admin.AdminBusinessManager">
    <property name="iAdminDAO" ref="iAdminDAO"></property>
    </bean>

    <bean id="iAdminDAO" class="tr.com.server.persistance.admin.AdminDAO">
    <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>     

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Index</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/application-config.xml</param-value>
    </context-param>

    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener> 

    <servlet>
        <servlet-name>springapp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springapp</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>45</session-timeout>
    </session-config>

    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>tr.com.server.webservice</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

休眠配置.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        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-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- HIBERNATE CONFIGURATION START POINT -->

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >
        <property name="packagesToScan" value="tr.com.server.model" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.pool_size">10</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.connection.release_mode">auto</prop>
                <prop key="hibernate.connection.characterEncoding">utf-8</prop>

                <!--HSQL -->
                <prop key="hibernate.connection.datasource">db2pool</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory
                </prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
            </props>
        </property>
    </bean>

    <!-- HIBERNATE CONFIGURATION END POINT -->

</beans>

springapp-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

</beans>

应用程序配置.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        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-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <import resource="hibernate-config.xml" />

    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager" />
    <aop:aspectj-autoproxy proxy-target-class="true" />
    <context:component-scan base-package="tr.com.server.webservice" />

    <import resource="xml/admin.xml" />

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

</beans>
4

1 回答 1

0

我在发布的代码中注意到两件事:

  1. AdminDAO a = new AdminDAO(); 不是通过弹簧工厂实例化。所以依赖的spring bean(包括会话工厂)将不会被连接。从 spring 上下文查找或自动连接中获取 AdminDAO bean。

  2. @Transactional 注解不会通过接口实现或子类化传播。也用 @Transactional 注释每个 DAO 类。

于 2013-04-21T21:52:50.687 回答