您的位置:首页 > 其它

s2s4h4框架整合之平台搭建(2)

2015-09-16 09:56 267 查看
本次文章主要是讲Spring4和hibernate4集成优化后的配置,看起来比之前的流畅,hibernate用注解,优化后,spring的属性参数配置可以直接让hibernate.cfg.xml消失,这样的话,这个项目的参数看起来就更加简洁和易懂了。同时介绍了下hibernate二级缓存的配置方式。

为了把相关重点的标红,我就不用编码格式了。

参考相关书籍的实例,编码通过了检测的,直接拷贝修改可以使用。需要的jar包由于ssh整合很多,就不再贴图了。

Spring的配置文件:

(1)默认配置文件classpath下: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"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- dao -->

<import resource="classpath:baobaotao-dao.xml"/>

<!-- service -->

<import resource="classpath:baobaotao-service.xml"/>

</beans>

(2)baobaotao-dao.xml 这个配置主要是封装数据来用的,所以主要是给持久层配置使用的(如hibernate等,注意开启二级缓存的配置)

<?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:p="http://www.springframework.org/schema/p"

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

<!-- 扫描dao组件中所有标注@Repository的dao组件 -->

<context:component-scan base-package="dao"></context:component-scan>

<!-- (1) 引入jdbc的属性文件 -->

<context:property-placeholder location="classpath:jdbc.properties" />

<!-- (2) 定义一个数据源 (本例采取的是c3p0数据源) -->

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="user" value="${jdbc.user}"></property>

<property name="password" value="${jdbc.password}"></property>

<property name="driverClass" value="${jdbc.driverClass}"></property>

<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>

<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>

</bean>

<!-- (3) 定义hibernate的sessionFactory(通过注解建立) -->

<bean id="sessionFactory"

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource">

<property name="packagesToScan" value="domain"
/>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

<!-- <prop key="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</prop>
-->

<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>

<prop key="hibernate.format_sql">true</prop>

<!--
hibernate事务托管给spring来管理就不用线程本地化了处理了 -->

<!--
<prop key="hibernate.current_session_context_class">thread</prop> -->

<!--
============================hibernate3或者是hibernate4二级缓存的配置======================================================================= -->

<!-- 开启二级缓存 -->

<prop key="hibernate.cache.use_second_level_cache">true</prop>

<!-- hibernate4二级缓存的实现类 -->

<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>

<!-- hibernate3二级缓存的实现类(本例是hibernate4所以注释掉,不然报错)-->

<!-- <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
-->

<!-- 开启查询缓存 -->

<prop key="hibernate.cache.use_query_cache">true</prop>

<prop key="net.sf.ehcache.configurationResourceName">/ehcache.xml</prop>

<!--
============================hibernate3或者是hibernate4二级缓存的配置======================================================================= -->

</props>

</property>

</bean>

<!-- (4) 定义hibernateTemplate -->

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"

p:sessionFactory-ref="sessionFactory"></bean>

</beans>

(3)baobaotao-service.xml 这个配置主要是给业务逻辑使用的,比如要进行AOP的注入等,本例中使用的是aop注入事务管理(其实使用注解的方式方式更加加单,就是<tx:annation-driven
transaction-managaer="...."/>,在相应的业务逻辑类上标注@Transaction采取默认配置,再在相应业务函数上标注@Transaction并配置特有个隔离机制等,用以覆盖并修改类标志的默认级别,萝卜白菜,各有所爱,看自己的喜好来配置)

<?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:tx="http://www.springframework.org/schema/tx"

xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

<!-- 扫描service报下所有标注@service组件 -->

<context:component-scan base-package="service"></context:component-scan>

<!-- 事务管理器(采用xml配置方式) hibernate事务托管交给了spring,就不用再配置threadLocal啦 -->

<bean id="transactionManager"

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"></bean>


<!-- 使用切面表达式配置 -->

<aop:config>

<aop:pointcut id="serviceMethod" expression="execution(* service.*Service.*(..))" />

<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />

</aop:config>

<!-- 事务增强 -->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="*" />

</tx:attributes>

</tx:advice>

</beans>

这里还有一点像强调的是,在以前的 《s2s4h4框架整合之平台搭建(1)》中,没有配置事务管理器托管给Spring,所以我们需要hibernate中需要配置threadLocal属性供事务使用,这里托管给Spring之后,就不用配置ThreadLocal属性了,即hibernate.current_session_context_class属性不用配置了。

(4)最后来看下SpringMVC:baobaotao-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:mvc="http://www.springframework.org/schema/mvc"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

<context:component-scan base-package="web"></context:component-scan>

<!-- 启动mvc的注解功能 -->

<mvc:annotation-driven></mvc:annotation-driven>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/"

p:suffix=".jsp"></bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"

p:defaultEncoding="utf-8"></bean>

<bean id="messageSource"

class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="i18n/message"/>

<!-- web异常解析处理 -->

<bean id="exceptionResolver" class="web.ForumHandlerExceptionResolver">

<property name="defaultErrorView">

<value>fail</value>

</property>

<property name="exceptionMappings">

<props>

<prop key="java.lang.RuntimeException">fail</prop>

</props>

</property>

</bean>

</beans>

最后的总结,分层结构的利用,让我们的程序加合理和容易,web.xml的配置基本一致,就不在贴出了,最后还有个旧市cache的配置文件,如下。

<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors. All third-party contributions are
~ distributed under license by Red Hat Middleware LLC.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA  02110-1301  USA
-->
<ehcache>

<!-- Sets the path to the directory where cache .data files are created.

If the path is a Java System Property it is replaced by
its value in the running VM.

The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="./target/tmp"/>

<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.

The following attributes are required for defaultCache:

maxInMemory       - Sets the maximum number of objects that will be created in memory
eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.

-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<!--Predefined caches.  Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts

The following attributes are required for defaultCache:

name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory       - Sets the maximum number of objects that will be created in memory
eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.

-->

<!-- Sample cache named sampleCache1
This cache contains a maximum in memory of 10000 elements, and will expire
an element if it is idle for more than 5 minutes and lives for more than
10 minutes.

If there are more than 10000 elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>

<!-- Sample cache named sampleCache2
This cache contains 1000 elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>

<!-- Place configuration for your caches following -->

</ehcache>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: