Spring——三大框架整合

Posted 想54256

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring——三大框架整合相关的知识,希望对你有一定的参考价值。

整合原理

整合步骤:

1、导包

2、单独配置Spring容器

导入约束(spring-config.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

配置spring随项目启动(web.xml)

<!-- 可以让spring容器随项目的启动而创建,随项目的关闭而销毁 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定加载spring配置文件的位置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-config.xml</param-value>
</context-param>

3、单独配置struts2

配置核心过滤器

<!--配置struts2核心过滤器-->
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4、struts2与spring整合

配置常量(Struts.xml)

<!--将struts对象交给Spring创建-->
<constant name="struts.objectFactory" value="spring"></constant>

配置spring负责创建action以及组装

spring-config.xml

<!-- action -->
<!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 -->
<bean name="userAction" class="cn.x5456.web.action.UserAction" scope="prototype">
    <property name="userService" ref="userService"></property>
</bean>

Struts.xml

<package name="crm" namespace="/" extends="struts-default">

    <!--配置全局异常-->
    <global-exception-mappings>
        <exception-mapping exception="java.lang.RuntimeException" result="error"></exception-mapping>
    </global-exception-mappings>

    <action name="UserAction_*" class="userAction" method="{1}">  <!--将class的值改为Spring管理对象的名字-->
        <result name="error" type="redirect">/login.jsp</result>
        <result name="success" type="redirect">/index.htm</result>
        <allowed-methods>login</allowed-methods>
     </action>
</package>

5、单独配置hibernate

导入实体类&orm元数据

配置文件

<?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>

		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		 <!-- 数据库url -->
		<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/xingedb</property>
		 <!-- 数据库连接用户名 -->
		<property name="hibernate.connection.username">root</property>
		 <!-- 数据库连接密码 -->
		<property name="hibernate.connection.password">xxx</property>
		<!-- 数据库方言-->

		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- 将hibernate生成的sql语句打印到控制台 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 将hibernate生成的sql语句格式化(语法缩进) -->
		<property name="hibernate.format_sql">true</property>
		<!-- 自动更新表,没有创建 -->
		<property name="hibernate.hbm2ddl.auto">update</property>

		<!--Spring会管理事务,session与线程绑定,所以要注释掉************************-->
		<!--事务隔离级别-->
		<!--<property name="hibernate.connection.isolation">4</property>-->
		<!--session与线程绑定-->
		<!--<property name="hibernate.current_session_context_class">thread</property>-->
		
		<!-- 引入orm元数据,路径书写: 填写src下的路径 -->
		<mapping resource="cn/x5456/domain/Customer.hbm.xml" />
		<mapping resource="cn/x5456/domain/LinkMan.hbm.xml" />
		<mapping resource="cn/x5456/domain/User.hbm.xml" />
		<mapping resource="cn/x5456/domain/Role.hbm.xml" />

	</session-factory>
</hibernate-configuration>

6、spring整合hibernate

将sessionFactory对象交给spring容器管理(此时可以不要hibernate.xml配置文件)

  <!--配置SessionFactory到容器中-->
    <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

        <!-- 配置hibernate基本信息 -->
        <property name="hibernateProperties">
            <props>
                <!--  必选配置 -->
                <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.url" >jdbc:mysql:///xingedb</prop>
                <prop key="hibernate.connection.username" >root</prop>
                <prop key="hibernate.connection.password" >xxx</prop>
                <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>

                <!--  可选配置 -->
                <prop key="hibernate.show_sql" >true</prop>
                <prop key="hibernate.format_sql" >true</prop>
                <prop key="hibernate.hbm2ddl.auto" >update</prop>
            </props>
        </property>
        <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
        <property name="mappingDirectoryLocations" value="classpath:cn/x5456/domain" ></property>
    </bean>

7、spring整合c3p0连接池

准备db.properties

#加一个(任意)前缀,防止与关键字冲突
jdbc.jdbcUrl=jdbc:mysql:///xingedb
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=xxx

配置文件

<!--1.设置读取db.properties文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

<!--2.设置连接池-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="DriverClass" value="${jdbc.driverClass}"></property>
    <property name="JdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="User" value="${jdbc.user}"></property>
    <property name="Password" value="${jdbc.password}"></property>
</bean>


<!--配置SessionFactory到容器中-->
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

    <!--3.将连接池注入sessionFactory-->
    <property name="dataSource" ref="dataSource"></property>

    <!-- 配置hibernate基本信息 -->
    <property name="hibernateProperties">
        <props>
            <!--  必选配置,由于使用连接池(在连接池中配置),就不用这4项了 -->
            <!--<prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>-->
            <!--<prop key="hibernate.connection.url" >jdbc:mysql:///xingedb</prop>-->
            <!--<prop key="hibernate.connection.username" >root</prop>-->
            <!--<prop key="hibernate.connection.password" >710130520a</prop>-->
            <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>

            <!--  可选配置 -->
            <prop key="hibernate.show_sql" >true</prop>
            <prop key="hibernate.format_sql" >true</prop>
            <prop key="hibernate.hbm2ddl.auto" >update</prop>
        </props>
    </property>
    <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
    <property name="mappingDirectoryLocations" value="classpath:cn/x5456/domain" ></property>
</bean>

8、spring整合hibernate环境操作数据库

查询方法:

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {  // 通过集成HibernateDaoSupport,获取HibernateTemplate

    
    public User getUserByUsercode(String user_code) {
     // 方法一:hql查询
        User u = super.getHibernateTemplate().execute(new HibernateCallback<User>() {
            @Override
            public User doInHibernate(Session session) throws HibernateException {

                String hql = "from User where user_code=?";
                Query query = session.createQuery(hql);
                query.setParameter(0, user_code);
                User u = (User) query.uniqueResult();

                return u;
            }
        });

        return u;

        // 方法二:Criteria查询
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);    // 离线对象

        dc.add(Restrictions.eq("user_code",user_code));

        List<User> list = (List<User>) super.getHibernateTemplate().findByCriteria(dc);  // 只返回list

        if (list!=null&&list.size()>0){
            return list.get(0);
        }else {
            return null;
        }
    }
}

需要提供sessionfactory对象

<bean name="userDao" class="cn.x5456.dao.impl.UserDaoImpl">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

9、Hibernate版AOP事务

核心事务管理器(只有这个和JDBC版<注入连接池>不同)

<!-- 核心事务管理器 -->
<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
    <property name="sessionFactory" ref="sessionFactory" ></property>
</bean>

方法一:配置通知 并 织入

<!-- 配置通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
    </tx:attributes>
</tx:advice>
<!-- 配置将通知织入目标对象,配置切点,配置切面 -->
<aop:config>
    <aop:pointcut expression="execution(* cn.x5456.service.impl.*ServiceImpl.*(..))" id="txPc"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>

方法二:配置注解事务

<!-- 开启注解事务,一定要开启注解扫描:<context:component-scan base-package="xxx.xxx.xxx"/> -->
<tx:annotation-driven transaction-manager="transactionManager" />

10、扩大session作用范围

为了避免使用懒加载时出现no-session问题.需要扩大session的作用范围

配置filter

<!-- 扩大session作用范围
注意: 任何filter一定要在struts的filter之前调用(因为如果Struts的拦截器没有放行,就根本走不了我们的filter)
-->
<filter>
    <filter-name>openSessionInView</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<!--配置struts2核心过滤器-->
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>openSessionInView</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

以上是关于Spring——三大框架整合的主要内容,如果未能解决你的问题,请参考以下文章

SSM三大框架整合

SSH框架第三季 - Spring5入门与三大框架整合

07-spring之三大框架的整合

转 :手动配置三大框架整合:Spring+Struts2+mybatis

(转)hibernate-5.0.7+struts-2.3.24+spring-4.2.4三大框架整合

SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)