`

SpringMVC+Spring+Hibernate+EHCache

阅读更多

maven构建SpringMVC+Spring+Hibernate+EHCache项目

1、首先使用maven构建一个web项目,目录结构如下

 

2、配置pom.xml

<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.1.4.RELEASE</spring.version>
		<hibernate.version>4.3.8.Final</hibernate.version>
		<jackson.version>2.5.0</jackson.version>
		<cxf.version>2.7.5</cxf.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-context-support</artifactId>
	      <version>${spring.version}</version>
	    </dependency>

		<!-- 使用SpringMVC需配置 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- 二级缓存ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.9.0</version>
		</dependency>

		<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

		<!-- mysql连接 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>

		<!-- c3p0数据源 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5-pre10</version>
		</dependency>
	</dependencies>

3、配置数据源、SessionFactory、二级缓存 ehcache、事务管理器 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.1.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
	
	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 扫描service自动注入为bean -->
	<context:component-scan base-package="com.tzz.web,com.tzz.hessian.service,com.tzz.aop,com.tzz.job.springtask" />
	
	<!-- 配置数据源 c3p0 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${jdbc.driver}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 请求超时时间 -->
		<property name="checkoutTimeout" value="30000" />
		<!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
		<property name="idleConnectionTestPeriod" value="30" />
		<!-- 连接数据库连接池最大空闲时间 -->
		<property name="maxIdleTime" value="30" />
		<!-- 连接池初始化连接数 -->
		<property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
		<property name="minPoolSize" value="${c3p0.pool.size.min}" />
		<property name="maxPoolSize" value="${c3p0.pool.size.max}" />
		<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
		<property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
	</bean>

	<!-- 配置hibernate的SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 注入数据源 相关信息看源码 -->
		<property name="dataSource" ref="dataSource" />
		<!-- hibernate配置信息 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>

				<!-- 开启二级缓存 ehcache -->
				<!-- 默认情况下二级缓存只会对load get 之类的方法缓存 -->
				<!-- 想支持list iterator 之类的方法也使用缓存,必须跟查询缓存一起使用,重写查询方法加上 .setCacheable(true) -->
				<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
				<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
				<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
				<prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
				</prop>
			</props>
		</property>
		<!-- 扫描hibernate注解配置的entity -->
		<property name="packagesToScan" value="com.tzz.web.domain" />
	</bean>

	<!-- 配置事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
<!-- 声明使用注解式事务 <tx:annotation-driven transaction-manager="transactionManager"/> -->
	<!-- 配置事务增强处理Bean,指定事务管理器 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<!-- 配置详细事务处理语义 -->
		<tx:attributes>
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="batch*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="new*" propagation="REQUIRED" isolation="DEFAULT" />

			<tx:method name="get*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true" />
			<tx:method name="find*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true" />
			<tx:method name="select*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true" />
			<tx:method name="load*" propagation="SUPPORTS" isolation="DEFAULT" read-only="true" />

			<!-- 其他采用默认事务方式 -->
			<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" />
		</tx:attributes>
	</tx:advice>

	<!-- Spring aop事务管理 -->
	<aop:config>
		<!-- 配置切入点 -->
		<aop:pointcut id="transactionPointcut" expression="execution(* com.tzz.web.service..*Impl.*(..))" />
		<!-- 指定在txAdvice切入点应用txAdvice事务增强处理 -->
		<aop:advisor pointcut-ref="transactionPointcut"
			advice-ref="transactionAdvice" />
	</aop:config>
	
</beans>

  
   3.1、jdbc.properties

 

#jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/webdemo?useUnicode=true&amp;characterEncoding=UTF8
jdbc.username=root
jdbc.password=root123

c3p0.pool.size.max=10
c3p0.pool.size.min=2
c3p0.pool.size.ini=3
c3p0.pool.size.increment=2
#hibernate config
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
#hibernate cache
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path=ehcache.xml

    3.2、缓存配置

       3.2.1、ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
	<diskStore path="D:/ehcache" />
	<!-- DefaultCache setting. -->
	<defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" 
	maxElementsOnDisk="1000000" overflowToDisk="true" memoryStoreEvictionPolicy="LRU">
	</defaultCache>
	
	<!-- 
        配置自定义缓存
        name:cache唯一标识   
        maxElementsInMemory:缓存中最大缓存对象数
        eternal:缓存中对象是否永久有效 ,如果是,超时设置将被忽略,对象从不过期。
        timeToIdleSeconds:缓存清除时间,
               缓存数据的钝化时间,也就是在一个元素消亡之前, 两次访问时间的最大时间间隔值,
               这只能在元素不是永久驻留时有效, 如果该值是 0 就意味着元素可以停顿无穷长的时间。
        timeToLiveSeconds:缓存存活时间 ,
                缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
                这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
        overflowToDisk:内存不足时,是否启用磁盘缓存。
        memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
        1.FIFO:first in first out 先讲先出  
        2.LFU: Less Frequently Used 一直以来最少被使用的  
        3.LRU:Least Recently Used  最近最少使用的   
    -->
 
	<cache name="com.tzz.web.domain.User" maxElementsInMemory="2"
		memoryStoreEvictionPolicy="LRU" eternal="true" diskPersistent="false"
		overflowToDisk="false" maxElementsOnDisk="1000000" />

</ehcache>

        3.2.2、Entity配置缓存

       @Entity

       @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="javaClassName")

 

       @Table(name = "tab_file_model")

       3.2.3、默认情况下二级缓存只会对load get 之类的方法缓存, 想支持list iterator 之类的方法也使用缓存,必须跟查询缓存一起使用,重写查询方法加上 .setCacheable(true)

 

4、配置SpringMVC( springMVC-servlet.xml)

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.1.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

	<!-- 自动扫描@Controller注入为bean -->
	<context:component-scan base-package="com.tzz.web.controller" />

	<!-- 以下为SpringMVC配置 -->
	<mvc:annotation-driven>
		<!-- 返回json数据,@response使用 -->
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>

			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/views" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	
	<!-- 拦截所有请求-->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**" />
			<bean class="com.tzz.web.context.LoginInterceptor">
				<property name="excludeStartsUris">
					<list>
					    <value>/index</value>
					</list>
				</property>
			</bean>
		</mvc:interceptor>
	</mvc:interceptors> 
	
	<!-- 支持上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
          p:defaultEncoding="utf-8">
        <property name="maxUploadSize">
            <value>1024000000</value>
        </property>
        <property name="maxInMemorySize">
            <value>409600</value>
        </property>
    </bean>

</beans>

5、配置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>web-demo</display-name>

	<!-- 配置contextConfigLocation 通过上下文参数指定spring配置文件的位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml,classpath:cxf-webservice.xml</param-value>
	</context-param>

	<!-- 配置ContextLoaderListener 保证服务启动时完成spring初始化 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 防止spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- openSessionInView配置 作用是延迟session关闭到view层 -->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!--整合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>/WEB-INF/classes/spring-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>

	<!-- 配置字符编码UTF-8 -->
	<filter>
		<filter-name>Character</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>Character</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 配置session超时时间,单位分钟 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
	
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics