Spring学习笔记(四)三大框架整合

一、三大框架架构

在这里插入图片描述

二、导包

hibernate
hibernate/lib/required:9个包:
在这里插入图片描述
hibernate/lib/jpa:规范包hibernate-entitymanager
数据库驱动:mysql-connector-java

struts2
struts-blank.war/WEB-INF/lib/*:13个包(有一个和上面重复了,删掉)13
struts整合spring插件包:struts2-spring-plugin(这个包导入后,struts2在启动的时候就会寻找spring容器。找不到会抛异常)

spring
基本包4+2: core+beans+context+expression,logging+log4j
整合web: spring-web
整合aop: spring-aop/spring-aspect/aop联盟/aop-weaving
整合jdbc和事务:spring-jdbc/spring-tx/c3p0/spring-orm
Junit测试: spring-test

标签库
standard.jar
jstl-1.2.jar

三、单独配置spring容器

1.创建配置文件,导入四个约束:beans|context|aop|tx
在这里插入图片描述

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

2.配置spring随项目启动 web.xml

  <!-- 让spring随web启动而创建的监听器 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 配置spring配置文件位置参数 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>

四、单独配置struts2

1.struts2的主配置文件

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<package name="crm" namespace="/" extends="struts-default">
		<action name="UserAction_*" class="cn.itcast.web.action.UserAction" method="{1}">
			<result name="toHome" type="redirect">/index.htm</result>
		</action>
	</package>
</struts>

2.配置struts2核心过滤器到web.xml

  <!-- 配置struts2的核心过滤器 -->
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

五、spring和struts2整合

1.需要jar包:struts2-spring-plugin
2.配置常量:将action的创建交给spring容器

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 	 	#struts.objectFactory = spring					将action的创建交给spring容器
			 struts.objectFactory.spring.autoWire = name 	spring负责装配action的依赖属性-->
	<constant name="struts.objectFactory" value="spring"></constant>
	<package name="crm" namespace="/" extends="struts-default">
		<action name="UserAction_*" class="cn.itcast.web.action.UserAction" method="{1}">
			<result name="toHome" type="redirect">/index.htm</result>
		</action>
	</package>
	
</struts>

3.具体整合
整合方案一:class属性上仍然配置action的完整类名:cn.itcast.web.action.UserAction,struts2自己创建action,spring负责组装依赖属性
在这里插入图片描述
不推荐:最好由spring完整管理action的生命周期.spring中功能才应用到Action上.
整合方案二:class属性上填写spring中action对象的BeanName:userAction
完全由spring来管理action的生命周期,包括action的创建
注意:需要手动组装依赖属性

在这里插入图片描述

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

六、单独配置hibernate

1.导入实体类&orm元数据
在这里插入图片描述
2.配置主配置文件
在这里插入图片描述

七、spring整合Hibernate

1.整合原理:将sessionFactory对象交给spring容器管理
2.在spring中配置sessionFactory
配置方案一:仍然使用外部的hibernate.cfg.xml配置信息

	<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	</bean> 

配置方案二:在spring配置中放置hibernate配置信息

	<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:///crm_32</prop>
				<prop key="hibernate.connection.username" >root</prop>
				<prop key="hibernate.connection.password" >root</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/itcast/domain" >
		</property>
	</bean>

八、spring整合c3p0连接池

1.配置db.properties

jdbc.jdbcUrl=jdbc:mysql:///crm_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

2.引入连接池到spring中

	<!-- 读取db.properties文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- 配置c3p0连接池 -->
	<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
		<property name="driverClass" value="${jdbc.driverClass}" ></property>
		<property name="user" value="${jdbc.user}" ></property>
		<property name="password" value="${jdbc.password}" ></property>
	</bean>

3.将连接池注入给sessionFactory

	<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!--  将连接池注入到sessionFactory, hibernate会通过连接池获得连接 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配hibernate基本信息 -->
		<property name="hibernateProperties">
			<props>
				<!--  必选配置 -->
				<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/itcast/domain" >
		</property>
	</bean>

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

1.Dao类创建:继承HibernateDaoSupport

public class UserDaoImpl extends HibernateDaoSupport implements UserDao

2.hibernate模板操作
方式一.execute

	@Override
	public User getByUserCode(final String usercode) {
		//HQL
		return 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, usercode);
					User user = (User) query.uniqueResult();
				return user;
			}
		});
		}

方式二.findByCriteria

	@Override
	public User getByUserCode(final String usercode) {
		//Criteria
		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		dc.add(Restrictions.eq("user_code", usercode));
		List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);
		if(list != null && list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}

3.spring中配置dao

	<!-- dao -->
	<bean name="userDao" class="cn.itcast.dao.impl.UserDaoImpl">
		<!-- 注入sessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

十、spring的aop事务

1.准备:核心事务管理器

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

2.1使用xml配置aop事务的方式
配置通知

<!-- 如果没有以下事务的通知+织入的配置,那么所有事务操作都默认只读 -->
<!-- 配置通知 -->	
<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.itcast.service.impl.*ServiceImpl.*(..))" id="txPc"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
	</aop:config>  

2.2使用注解配置aop事务
注:上面的事务模板和通知、织入等配置都可以注释掉了
开启注解事务

<!-- 开启使用注解配置事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

service类中使用注解

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class UserServiceImpl implements UserService{
	@Override
	@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
	public void saveUser(User u) {
		ud.save(u);
	}

十一、扩大session的作用范围

1.目的:为了避免使用懒加载时出现no-session问题.需要扩大session的作用范围
2.配置filter

  <!-- 扩大session的作用范围
  		注意:openSessionInView(也包括其他任何过滤器)一定要在struts的filter之前调用:因为struts的过滤器是不放行的
   -->
   <filter>
  	<filter-name>openSessionInView</filter-name>
  	<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>openSessionInView</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值