阅读 22

Spring5+Hibernate5+SpringMVC配置

记录一篇架构升级的文档,将配置过程遗漏的要点进行标注。以防自己日后遗忘。

Spring配置文件: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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

	<!-- 声明注解 @Autowired等 -->
	<context:annotation-config/>
    <context:component-scan base-package="com.demo.dao"/>
	<context:component-scan base-package="com.demo.service"/>
	<context:component-scan base-package="com.demo.*.dao"/>
	<context:component-scan base-package="com.demo.*.service"/>
	<!-- Spring中资源文件的解析locations里面配置的properties文件如果找不到的话,就可以忽略找不到的文件 -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<property name="ignoreResourceNotFound" value="true" />
	</bean>
	<!-- 解析资源文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="order" value="1"/>
    	<property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
        <property name="driverClass" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>  
        <property name="user" value="${jdbc.username}"/>  
        <property name="password" value="${jdbc.password}"/>
        <property name="initialPoolSize" value="${initialPoolSize}"/>  
        <property name="maxStatementsPerConnection" value="${maxStatementsPerConnection}"/>  
        <property name="maxPoolSize" value="${maxPoolSize}"/>  
        <property name="minPoolSize" value="${minPoolSize}" />  
        <property name="maxIdleTime" value="${maxIdleTime}" />  
    </bean> 
    
    <!-- 配置sessionFactory -->  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    	<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="dataSource" ref="dataSource"/> 
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">none</prop>
              <!--   <prop key="hibernate.show_sql">true</prop>   -->
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="jdbc.c3p0.testConnectionOnCheckout">${jdbc.c3p0.testConnectionOnCheckout}</prop>
                <prop key="jdbc.c3p0.testConnectionOnCheckin">${jdbc.c3p0.testConnectionOnCheckin}</prop>
                <prop key="jdbc.c3p0.testConnectionOnCheckout">${jdbc.c3p0.idleConnectionTestPeriod}</prop>
            </props>  
        </property>  
        <property name="packagesToScan" value="com.demo"/>
    </bean>
    <!-- 配置要扫描的注解  在spring中排除不扫描 -->  
    <context:component-scan base-package="com.demo" use-default-filters="false">  
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>  
    </context:component-scan>   
    <!-- 启动AspectJ支持 -->  
    <aop:aspectj-autoproxy/>  
    <!-- 配置事务管理器 -->  
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!-- 使用注解配置事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 配置事务传播特性 -->
     <!--6.事务-->  
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.RuntimeException"/>
			<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.RuntimeException"/>
			<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.RuntimeException"/>
			<tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.RuntimeException"/>
			<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="find*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="*" propagation="REQUIRED"/>
    	</tx:attributes>
    </tx:advice>
    <aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* com.demo.service.*.*(..))"/>
	<aop:advisor pointcut-ref="txPointCut" advice-ref="txAdvice" />
    </aop:config>
</beans>

复制代码

数据库jdbc.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/databaseName?serverTimezone=GMT%2B8&useSSL=false&rewriteBatchedStatements=true&autoReconnect=true&failOverReadOnly=false
jdbc.username=root
jdbc.password=root
initialPoolSize=5
maxStatementsPerConnection=15
maxPoolSize=100
minPoolSize=2
maxIdleTime=1000
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true
jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600
hibernate.hbm2ddl.auto=none
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
复制代码

SpringMVC配置文件:springMVC-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:context="http://www.springframework.org/schema/context"   
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"    
    xmlns:jee="http://www.springframework.org/schema/jee"   
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd  
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd  
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-4.3.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd  
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
 	<!-- 注解扫描包 -->
    <context:component-scan base-package="com.demo.controller" />
    <context:component-scan base-package="com.demo.interceptor" />
    <!-- 开启注解 -->
    <mvc:annotation-driven enable-matrix-variables="true"/>
     <!-- ViewResolver config -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--网页文件存放位置-->
      	<property name="prefix" value="/WEB-INF/view"/>       
        <!--相当于url后缀加上.jsp-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- jackson config -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    
        <property name="messageConverters">      
            <list >      
                <ref bean="mappingJacksonHttpMessageConverter" />      
            </list>      
        </property>      
    </bean>  
    <!--JSON格式转换  -->
   <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
    <property name="supportedMediaTypes">    
        <list>    
            <value>application/json;charset=UTF-8</value>
       </list>    
    </property>  
  </bean> 
     <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <property name="defaultEncoding" value="UTF-8"/>
         <!-- 指定所上传文件的总大小不能超过10M。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
         <property name="maxUploadSize" value="20480000"/>
     </bean>
	<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->  
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
            </props>  
        </property>  
    </bean>
         <!--配置过滤器 -->
	<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/customer/**" />
		<mvc:exclude-mapping path="/customer/public/*" /><!--不匹配的 -->
		<bean class="com.demo.interceptor.AuthorizedInterceptor"/>
	</mvc:interceptor>
	</mvc:interceptors>
</beans>复制代码

hibernate配置文件:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
        <!-- 匹配的POJO映射文件 -->   
        <mapping resource="/hibernate-conf/Customer.hbm.xml"></mapping>
        ······
    </session-factory>
</hibernate-configuration>
复制代码

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>demoservice</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
  <!-- 加载所有的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
  </context-param>

  <!-- 配置Spring监听 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 配置SpringMVC -->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:springMVC-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 配置字符集 -->
  <filter-mapping>
    <filter-name>VisitFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 配置Session -->
  <filter>
    <filter-name>openSession</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>openSession</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>复制代码

以上就是基本的配置文件的配置详情。如有错误请指正。

关注下面的标签,发现更多相似文章
评论