弹簧3.2.3的最佳配置

时间:2013-08-20 18:40:56

标签: spring hibernate spring-mvc

我试图了解弹簧配置。我读了两篇文章:

  1. http://www.onjava.com/pub/a/onjava/2006/03/22/advanced-spring-configuration.html?page=1
  2. http://syntx.io/difference-between-loading-context-via-dispatcherservlet-and-contextloaderlistener/
  3. 这些建议有2个配置文件:“Application Context”和“Web Application Context”。

      

    如果您曾尝试使用Spring MVC框架开发Web应用程序,您知道应该使用两个配置文件:

         

    /WEB-INF/applicationContext.xml允许您配置bean,或   表明您的申请的背景。这是哪里的地方   您定义业务逻辑bean,资源和所有其他bean   与网络层没有直接关系的。

         

    / WEB-INF / [servlet-name] -servlet.xml用于配置Web层   并查看解析器,控制器,验证器和所有其他bean   你需要在MVC框架中。 [servlet-name]指的是名称   在web.xml部署中定义的Spring的调度程序servlet   描述符。

    根据这个,我写了我的web.xml如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
    
        <!-- Application Context -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml,
                /WEB-INF/spring-security.xml</param-value>
        </context-param>
    
    
        <!-- Spring MVC -->
        <servlet>
            <servlet-name>mvc-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>mvc-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    
        <!-- Spring Security -->
        <filter>
            <filter-name>springSecurityFilterChain</filter-name>
            <filter-class>
                org.springframework.web.filter.DelegatingFilterProxy
            </filter-class>
        </filter>
    
        <filter-mapping>
            <filter-name>springSecurityFilterChain</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- Fin Spring Security -->
    
    </web-app>
    

    这是我的applicationContext.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:jee="http://www.springframework.org/schema/jee"
      xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.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.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
    
    
      <!-- Look in tom cats context -->
      <jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/rhcimax"/>
    
      <!-- Hibernate Session Factory -->
      <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan">
          <array>
            <value>com.blah.baseProject</value>
          </array>
        </property>
        <property name="hibernateProperties">
          <value>
            hibernate.dialect=org.hibernate.dialect.MySQLDialect
          </value>
        </property>
      </bean>
    
      <!-- Hibernate Transaction Manager -->
      <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
      </bean>
    
      <!-- Activates annotation based transaction management -->
      <tx:annotation-driven transaction-manager="transactionManager"/>
    
    </beans>
    

    这是我的mvc-dispatcher-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"
      xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.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.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
      <!-- Enable @Controller annotation support -->
      <mvc:annotation-driven />
    
      <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
      <mvc:resources mapping="/resources/**" location="/resources/" />
    
      <!-- Map simple view name such as "test" into /WEB-INF/views/test.jsp -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/view/" />
        <property name="suffix" value=".jsp" />
      </bean>
    
      <!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
      <context:component-scan base-package="com.blah.baseProject"/>
    
    
    </beans>
    

    我想知道这个配置是否几乎正确。这个配置运行但我觉得没有调用applicationContext.xml,因为我得到了这个异常:

    org.hibernate.HibernateException: No Session found for current thread
    

    我的目的是在春季保持良好的实践并学习正确的配置。

      

    &#34;最佳做法是在中间层之间保持清晰的分离   业务逻辑组件和数据访问类等服务   (通常在ApplicationContext中定义)和web-   相关组件,如控制器和视图解析器(即   在每个Dispatcher Servlet的WebApplicationContext中定义。&#34;

2 个答案:

答案 0 :(得分:5)

您可以将web.xml上下文参数更改为:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>

创建任意数量的上下文文件,而不将其导入根上下文

enter image description here

当你有多模块项目并将配置文件放到每个模块时,它非常有用,将它命名为applicationContext-.xml,它将被自动扫描。

最好在mvc-dispatcher-servlet.xml中声明mvc组件:拦截器(locale,主题拦截器和您自己的),视图解析器,资源,异常处理程序,模板引擎配置以及与之相关的其他组件视图。

此外,仅为servlet配置中的控制器声明组件扫描非常有用:

MVC-调度-servlet.xml中:

<context:component-scan base-package="by.company.app" use-default-filters="false">
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>

在applicationContext中排除@Controller扫描:

的applicationContext.xml:

<context:component-scan base-package="by.company.app">
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>

这有助于避免重复的bean定义

单独的applicationContexts示例(省略名称空间声明):

的applicationContext.xml:

<beans>    
    <context:property-placeholder location="classpath*:META-INF/spring/a-*.properties" />

    <task:annotation-driven/>

    <context:spring-configured/>

    <context:component-scan base-package="by.company.app">
        <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
    </context:component-scan>
</beans>

的applicationContext-db.xml

<beans>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="jdbc:mysql://${database.host}:${database.port}/${database.db-path}" />
        <property name="driverClassName" value="${database.driverClassName}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" /> 
    </bean>

    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>

    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="persistenceUnitName" value="persistenceUnit"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties"> 
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.max_fetch_depth">3</prop> 
                <prop key="hibernate.jdbc.fetch_size">50</prop> 
                <prop key="hibernate.jdbc.batch_size">10</prop> 
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
                <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
            </props> 
        </property>
    </bean>

    <jpa:repositories base-package="by.company.app" />

</beans>

答案 1 :(得分:2)

根据我的经验,只要您没有任何具体理由将核心配置与webapp配置分开,最好的方法是将DispatcherServlet的上下文保持为空并将所有内容放入根应用程序上下文中( applicationContext.xml等。)

通过这样做,您可以避免许多可能的问题,特别是:

  • <tx:annotation-driven>等后处理器应该基于每个上下文声明(这是你的问题)。如果servlet的上下文中没有bean,则不需要在那里复制这些声明
  • 在两个上下文中为同一个包声明<context:component-scan>会导致重复的bean定义出现严重问题

如果您担心单个上下文的可管理性,请记住您仍然可以将其拆分为多个文件,就像您已经做的那样。

请注意,如果DispatcherServlet从XML文件中读取上下文配置(默认情况下已配置),则仍需要创建具有有效根元素的XML文件。但是,有一个小技巧:如果您将DispatcherServlet配置为使用基于注释的配置,则默认情况下它将为空,无需任何额外工作:

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>