弹簧3.2.3的最佳配置

kid*_*uxa 3 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/

这些建议有2个配置文件:"应用程序上下文"和"Web应用程序上下文".

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

/WEB-INF/applicationContext.xml允许您配置bean,或指示应用程序的上下文.您可以在此处定义业务逻辑bean,资源以及与Web层不直接相关的所有其他Bean.

/WEB-INF/[servlet-name]-servlet.xml用于配置Web层并查看MVC框架中需要的解析器,控制器,验证器和所有其他bean.[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>
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

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

org.hibernate.HibernateException: No Session found for current thread
Run Code Online (Sandbox Code Playgroud)

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

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

yna*_*ame 5

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

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

并创建任何上下文文件计数而不将其导入根上下文

在此输入图像描述

当你有多模块项目并将配置文件放到每个模块时,它非常有用,命名为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>
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)

这有助于避免重复的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>
Run Code Online (Sandbox Code Playgroud)

的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>
Run Code Online (Sandbox Code Playgroud)