标签:测试的 产生 下载地址 自动注入 eth 可重复 ssr 维护 Servle
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。Spring的核心是控制反转(IoC)和面向切面(AOP)。简单来说,Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架。
◆JAVA EE应该更加容易使用。
◆面向对象的设计比任何实现技术(比如JAVA EE)都重要。
◆面向接口编程,而不是针对类编程。Spring将使用接口的复杂度降低到零。(面向接口编程有哪些复杂度?)
◆代码应该易于测试。Spring框架会帮助你,使代码的测试更加简单。
◆JavaBean提供了应用程序配置的最好方法。
◆在Java中,已检查异常(Checked exception)被过度使用。框架不应该迫使你捕获不能恢复的异常。
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。
◆ IOC 就是把创建对象的控制权交给Spring来管理,我们只要向容器提出需求,容器就会按需求提供相应的对象,这就叫"控制反转"
◆ DI(依赖注入) 多个对象之间会存在相应关系,我们把其它对象作为属性值传递给其它的对象做为其内部的一部分.(设置对象之间的关联关系)
3.1 什么是耦合?
对象之间产生的一种关联关系
◆ 强耦合:就是在编译器就产生了关联关系
◆ 硬编码
◆ 不利于维护和扩展
◆ 低耦合:就是在运行期间让对象之间产生关联
◆ 使用反射来创建对来
◆ 对象的完整限定名放到配置文件中
◆ 解决了硬编码问题,有利于程序后期的维护和扩展
Spring IOC 容器就能帮们解决以上的问题
下载地址:https://spring.io/
1. 导入Spring jar包
2. 配置Spring核心配置文件(applicationContext.xml) (bean标签配置需要创建的对象)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/bean 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> 6 <!--给Spring容器配置Bean--> 7 <bean id="student" class="com.hwua.entity.Student"></bean> 8 </beans>
3. 编写测试类
package com.hwua.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hwua.entity.Student;
public class SpringTest {
@Test
public void test() {
//创建一个工厂,根据配置文件来创建对象放到容器中,通过工厂可以从容器中获取对象
//初始化IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student)context.getBean("student");
System.out.println(student);
}
}
5.1 Spring 构建Bean对象的方式
◆ 使用反射去创建对象,默认会调用无参构造函数(重点)
1 <bean id="userService" class="com.hwua.service.impl.UserServiceImpl"></bean>
◆ 使用普通工厂来创建对象
1 package com.hwua.factory; 2 import com.hwua.dao.UserDao; 3 import com.hwua.dao.impl.UserDaoJDBCImpl; 4 /** 5 * 普通工厂类 6 * 7 * @author Administrator 8 * 9 */ 10 public class BeanFactroy1 { 11 public UserDao createUserDao() { 12 return new UserDaoJDBCImpl(); 13 } 14 }
◆ 使用静态工厂来创建bean对象
package com.hwua.factory; import com.hwua.dao.UserDao; import com.hwua.dao.impl.UserDaoJDBCImpl; import com.hwua.dao.impl.UserDaoMyBatisImpl; /** * 静态工厂类 * * @author Administrator * */ public class BeanFactroy2 { public static UserDao createUserDao() { return new UserDaoMyBatisImpl(); } }
然后在spring的配置文件中 配置 userDaoMyBatis对象,条用静态工厂中的createUserDao方法
<bean id="userDaoMyBatis" class="com.hwua.factory.BeanFactroy2" factory-method="createUserDao"></bean>
6.XML注入方式
1. 构造器注入(会用)
1 <!--可以直接给value属性赋值,但必须值的顺序按照构造函数参数的顺序,否则课程存在出错 --> 2 <constructor-arg value="1"></constructor-arg> 3 <constructor-arg value="陈豪"></constructor-arg> 4 <constructor-arg value="20"></constructor-arg> 5 6 <!--可以指定index属性来控制参数赋值的顺序 --> 7 <constructor-arg value="陈豪" index="1"></constructor-arg> 8 <constructor-arg value="1" index="0"></constructor-arg> 9 <constructor-arg value="20" index="2"></constructor-arg> 10 <!--我们可以使用index,name,type来控制构造器注入参数的顺序--> 11 <constructor-arg value="20" type="java.lang.Integer" index="2"></constructor-arg> 13 <constructor-arg value="陈豪" type="java.lang.String"></constructor-arg> 15 <constructor-arg value="1" type="java.lang.Integer" name="age"></constructor-arg> 17 记住只要记住使用name,根据参数的名来来进行赋值 18 <constructor-arg value="1" name="age"></constructor-arg>
2. set注入方式(重点)
◆ 基本类型数据的注入使用value属性来注入,自定义的引用数据类型使用ref来给属性注入
◆ set注入必须要有五参数构造函数,内部通过反射机制调用无参构造函数来创建对象的.
◆ 属性必须要有对象的get和set方法
1 <!--给Spring容器配置Bean --> 2 <bean id="student" class="com.hwua.entity.Student"> 3 <property name="id" value="1"></property> 4 <property name="name" value="zhangsan"></property> 5 <property name="age" value="30"></property> 6 <property name="car" ref="car"></property> 7 8 </bean> 9 10 <bean id="car" class="com.hwua.entity.Car"> 11 <property name="brand" value="奔驰"></property> 12 <property name="price" value="300000"></property> 13 </bean>
3. P命名空间注入方式(Spring2.5以后才有)
◆ 引入P命名空间
1 xmlns:p="http://www.springframework.org/schema/p" 2 xmlns:c="http://www.springframework.org/schema/c"
◆ 编写注入语法
1 <!--构造器注入--> 2 <bean id="student" class="com.hwua.entity.Student" c:_0="1" c:_1="张三" c:_2="30" c:_3-ref="car"></bean> 3 <bean id="car" class="com.hwua.entity.Car" c:_0="奔驰" c:_1="300000"></bean> 4 <!--属性注入--> 5 <bean id="car" class="com.hwua.entity.Car" p:brand="奔驰" p:price="300000"></bean> 6 <bean id="student" class="com.hwua.entity.Student" p:id="1" p:name="张三" p:age="30" p:car-ref="car"></bean>
4.spel(Spring Expression Language)注入方式
1 <bean id="car" class="com.hwua.entity.Car"> 2 <property name="brand" value="#{‘奔驰‘}"></property> 3 <property name="price" value="#{300000}"></property> 4 </bean> 6 <bean id="student" class="com.hwua.entity.Student"> 7 <property name="id" value="#{1+1}"></property> 8 <property name="name" value="#{‘zhangsan‘}"></property> 9 <property name="age" value="#{30}"></property> 10 <property name="car" value="#{car}"></property> 11 </bean>
5.复杂类型数据的注入
java实体类
1 package com.hwua.entity; 2 3 import java.util.List; 4 import java.util.Map; 5 import java.util.Properties; 6 import java.util.Set; 7 8 public class ComplexData { 9 private List<String> list; 10 private Set<String> set; 11 private Map<String, String> map; 12 private Properties properties; 13 private Car[] arr; 14 15 public List<String> getList() { 16 return list; 17 } 18 19 public void setList(List<String> list) { 20 this.list = list; 21 } 22 public Set<String> getSet() { 23 return set; 24 } 25 26 public void setSet(Set<String> set) { 27 this.set = set; 28 } 29 30 public Map<String, String> getMap() { 31 return map; 32 } 33 34 public void setMap(Map<String, String> map) { 35 this.map = map; 36 } 37 38 public Properties getProperties() { 39 return properties; 40 } 41 42 public void setProperties(Properties properties) { 43 this.properties = properties; 44 } 45 46 public Car[] getArr() { 47 return arr; 48 } 49 50 public void setArr(Car[] arr) { 51 this.arr = arr; 52 } 53 54 }
配置spring配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:c="http://www.springframework.org/schema/c" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> 8 <bean id="car1" class="com.hwua.entity.Car"> 9 <property name="brand"> 10 <!-- <value><![CDATA[1<2]]></value> --> 11 <null/> 12 </property> 13 <property name="price" value="40000"></property> 14 </bean> 15 <bean id="car2" class="com.hwua.entity.Car"> 16 <property name="brand" value="宝马"></property> 17 <property name="price" value="30000"></property> 18 </bean> 19 <bean id="car3" class="com.hwua.entity.Car"> 20 <property name="brand" value="奥迪"></property> 21 <property name="price" value="25000"></property> 22 </bean> 23 24 <bean id="data" class="com.hwua.entity.ComplexData"> 25 <!--List类型的属性注入 --> 26 <property name="list"> 27 <list> 28 <--引用数据类型的放入--> 29 <ref bean="放入的对象引用"/> 30 <--j基本数据类型的放入--> 31 <value>chenhao1</value> 32 <value>chenhao2</value> 33 <value>chenhao3</value> 34 <value>chenhao4</value> 35 </list> 36 </property> 37 38 <!--Set类型的属性注入 --> 39 <property name="set"> 40 <set> 41 <value>chenhao4</value> 42 <value>chenhao5</value> 43 <value>chenhao6</value> 44 <value>chenhao7</value> 45 </set> 46 </property> 47 48 <!--Map类型的属性注入 --> 49 <property name="map"> 50 <map> 51 <entry key="jack" value="老王"></entry> 52 <entry key="frank" value="老陈"></entry> 53 <entry key="mary" value="老李"></entry> 54 </map> 55 </property> 56 57 <!--Properties类型数据的属性注入 --> 58 <property name="properties"> 59 <props> 60 <prop key="frank">老王</prop> 61 <prop key="jack">老陈</prop> 62 <prop key="mary">老李</prop> 63 </props> 64 </property> 65 66 <!--数组类型数据的属性注入 --> 67 <property name="arr"> 68 <array> 69 <ref bean="car1"/> 70 <ref bean="car2"/> 71 <ref bean="car3"/> 72 </array> 73 </property> 74 </bean> 75 </beans>
1 - ClassPathXmlApplicationContext :加载类路径下的spring配置文件,相对定位 2 - FileSystemXmlApplicationContext:加载文件系统路径下的Spring配置文件,绝对定位(不推荐) 3 - AnnotationConfigApplicationContext:加载注解配置类,也就是说以后的配置信息写到一个配置类中,不用xml文件来作为配置文件(后续会讲)
1 - singleton 在容器中始终只产生一个对象 2 - prototype 在向容器获取多次bean的时候,会产生多个bean对象 3 - request 在request作用域中存入一个bean对象 4 - session 在session作用域中存入一个bean对象
◆ 单例(singon)时对象的生命周期
◆ 创建时机: 容器创建的时候对象创建
◆ 销毁时机: 容器关闭的时候对象就销毁
◆ 多例(prototype)时对象的生命周期
◆ 创建时机: 当要从容器中获取指定对象的时候,就会由Spring来创建一个对象,延迟创建
◆ 销毁时机:当对象长时间不被使用,或对象的引用为null的时候,有JVM的垃圾回收器来执行回收
◆ BeanFactory 是ApplicationContext接口的父接口,ApplicationContext功能更强大
◆ ApplicationContext 容器在创建的时候就会对配置文件的scope为singleton的对象进行统一创建,而BeanFactory容器在创建的时候不会对作用范围为singleton的对象进行统一创建,而是在获取对象的时候在创建.
◆ @Component 基本注释
◆ @Service 注释业务层
◆ @Controller 注释控制层
◆ @Resposity 注释持久层(dao层)
以上的功能完全一样,只是注解名字不同,在分层架构中可读性更好
◆ @AutoWired 自动注入,默认是根据类型来注入的,也就是说它会从容器中找唯一相关类型的对象注入进来
◆ @Primary 当有两个相同类型对象的时候,以@Primary修饰的对象来进行注入
◆ @Quali?er 往往 配合@AutoWired 来使用,先以类型来注入,当类型相同的时候再按@Quali?er指定的名字来注入,不能单独使用的
1 @Autowired 2 @Qualifier("userDaoMyBatis")
◆ @Resource 等同于@Autowired 和 @Quali?er的组合,假设不给name属性,默认按类型来注入,给name属性值,那就按名字来注入
◆ 以上几个注解都只能注入bean数据类型的数据,基础类型的数据(8大基本数据类型和String),是不能用上述注解来注入的
◆ @Scope("prototype") 注解 来声明对象在容器中作用范围,主要值sigleton和prototype
◆ @PostConstruct 修饰的方法就是对象创建时要执行的方法
◆ @PreDestroy 修饰的方法是在对象销毁的时候要执行的方法
◆ @Value 注解给属性赋值基本类型的数据
db.properties 连接数据库的配置
1 jdbc.driver=com.mysql.cj.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:7766/mybatisdb 3 jdbc.username=root 4 jdbc.password=12345678
11.1 Spring 整合 DBUtils 和 C3P0
<?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" 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.3.xsd">
<!--用来读取属性文件 --> <context:property-placeholder location="classpath:db.properties"/> <!--配置业务层对象 --> <bean id="userService" class="com.hwua.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <!--配置一个DAO对象 --> <bean id="userDao" class="com.hwua.dao.impl.UserDaoImpl"> <property name="qr" ref="runner"></property> </bean> <!--配置QueryRunner对象 --> <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> <!--配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> </beans>
11.2.Spring 整合 JDBCTemplate 和 DRUID
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 <!--用来读取属性文件 --> 10 <context:property-placeholder location="classpath:db.properties"/> 11 12 <!--配置业务层对象 --> 13 <bean id="userService" class="com.hwua.service.impl.UserServiceImpl"> 14 <property name="userDao" ref="userDao"></property> 15 </bean> 16 17 <!--配置一个DAO对象 --> 18 <bean id="userDao" class="com.hwua.dao.impl.UserDaoImpl"> 19 <property name="jTemplate" ref="jdbcTemplate"></property> 20 </bean> 21 <!--配置jdbcTemplate对象 --> 22 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 23 <property name="dataSource" ref="dataSource"></property> 24 </bean> 25 <!--配置DRUID数据源 --> 26 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 27 <property name="driverClassName" value="${jdbc.driver}"></property> 28 <property name="url" value="${jdbc.url}"></property> 29 <property name="username" value="${jdbc.username}"></property> 30 <property name="password" value="${jdbc.password}"></property> 31 </bean> 32 </beans>
11.3.Spring 整合junit (让测试类代码更简单)
◆ 我们一般通过main方法来运行程序
◆ 单元测试类其实它底层继承了一个main方法,当运行的时候会调用运行那些有@Test修饰的方法
◆ 我们可以使用Spring整合Junit来简化单元测试的复杂度
首先导入Spring-test jar包
测试类写法
1 package com.hwua.test; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.annotation.Qualifier; 7 import org.springframework.context.ApplicationContext; 8 import org.springframework.context.support.ClassPathXmlApplicationContext; 9 import org.springframework.test.context.ContextConfiguration; 10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 import com.hwua.service.AccountService; 12 13 @RunWith(SpringJUnit4ClassRunner.class) 14 @ContextConfiguration("classpath:beans.xml") 15 public class AccountTest { 16 @Autowired 17 private AccountService accountService=null; 18 @Test 19 public void testAccount() { 20 // 创建SpringIOC容器,context 就是IOC容器的引用 21 // 用spring整合单元测试后,就不需要写下面两行代码 ,因为spring单元测试会自动创建的 22 // ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); 23 // AccountService accountService =(AccountService)context.getBean("userService"); 24 try { 25 accountService.transferMoney("zhangsan", "lisi", 1000); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 } 30 }
11.4.Spring 整合 MyBatis 和 DRUID
首先导入MyBatis的jar包,mybatis-spring整合包,spring-jdbc 事务处理包
pom.xml文件中的依赖配置
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <groupId>com.hwua</groupId> 6 <artifactId>Spring_Day3_Spring_MyBatis</artifactId> 7 <version>0.0.1-SNAPSHOT</version> 8 <dependencies> 9 <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> 10 <!-- spring包 --> 11 <dependency> 12 <groupId>org.springframework</groupId> 13 <artifactId>spring-context</artifactId> 14 <version>5.1.5.RELEASE</version> 15 </dependency> 16 <!-- 单元测试包 --> 17 <dependency> 18 <groupId>junit</groupId> 19 <artifactId>junit</artifactId> 20 <version>4.12</version> 21 </dependency> 22 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> 23 <!-- mybatis和spring整合包 --> 24 <dependency> 25 <groupId>org.mybatis</groupId> 26 <artifactId>mybatis-spring</artifactId> 27 <version>2.0.0</version> 28 </dependency> 29 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> 30 <!-- mybatis包 --> 31 <dependency> 32 <groupId>org.mybatis</groupId> 33 <artifactId>mybatis</artifactId> 34 <version>3.4.6</version> 35 </dependency> 36 <!-- 阿里巴巴Druid --> 37 <dependency> 38 <groupId>com.alibaba</groupId> 39 <artifactId>druid</artifactId> 40 <version>1.1.16</version> 41 </dependency> 42 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> 43 <!-- 数据库连接包 --> 44 <dependency> 45 <groupId>mysql</groupId> 46 <artifactId>mysql-connector-java</artifactId> 47 <version>8.0.15</version> 48 </dependency> 49 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> 50 <!-- 依赖事物处理包 --> 51 <dependency> 52 <groupId>org.springframework</groupId> 53 <artifactId>spring-jdbc</artifactId> 54 <version>5.1.5.RELEASE</version> 55 </dependency> 56 </dependencies> 57 </project>
applicationContext配置文件
◆ 第一种配置方式,有spring配置文件和mybatis配置文件
spring配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 <!--读取类路径下的配置db.properties文件 --> 10 <context:property-placeholder location="classpath:db.properties"/> 11 <!-- 开启注释扫描 --> 12 <context:component-scan base-package="com.hwua.service"></context:component-scan> 14 <bean id="userService" class="com.hwua.service.impl.UserServiceImpl"></bean> 15 <!--Spring整合MyBatis --> 16 <bean id="sqlSessionFatory" class="org.mybatis.spring.SqlSessionFactoryBean"> 18 <property name="dataSource" ref="dataSource"></property> 19 <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property> 21 </bean> 22 <!--配置扫描Mapper接口类型的数据,把接口类型的对象放入Spring容器中 --> 23 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 24 <!--配置包扫描 --> 25 <property name="basePackage" value="com.hwua.mapper"></property> 26 <property name="sqlSessionFactoryBeanName" value="sqlSessionFatory"> </property> 28 </bean> 29 <!--配置DRUID数据源 --> 30 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 31 <property name="driverClassName" value="${jdbc.driver}"></property> 32 <property name="url" value="${jdbc.url}"></property> 33 <property name="username" value="${jdbc.username}"></property> 34 <property name="password" value="${jdbc.password}"></property> 35 </bean> 36 </beans>
mybatis配置文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!--配置一个别名包扫描 --> 7 <typeAliases> 8 <package name="com.hwua.pojo"/> 9 </typeAliases> 10 <mappers> 11 <package name="com.hwua.mapper"/> 12 </mappers> 13 </configuration>
◆ 第二种:省略MyBatis配置文件的方式
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 <!--读取类路径下的配置db.properties文件 --> 10 <context:property-placeholder location="classpath:db.properties"/> 11 <bean id="userService" class="com.hwua.service.impl.UserServiceImpl"></bean> 12 <!--Spring整合MyBatis --> 13 <bean id="sqlSessionFatory" 14 class="org.mybatis.spring.SqlSessionFactoryBean"> 15 <property name="dataSource" ref="dataSource"></property> 16 <property name="typeAliasesPackage" value="com.hwua.pojo"></property> 17 <property name="mapperLocations" value="classpath:com/hwua/mapper/*.xml"></property> 19 </bean> 20 <!--配置扫描Mapper接口类型的数据,把接口类型的对象放入Spring容器中 --> 21 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 22 <!--配置包扫描 --> 23 <property name="basePackage" value="com.hwua.mapper"></property> 24 <property name="sqlSessionFactoryBeanName" value="sqlSessionFatory"> 25 </property> 26 </bean> 27 <!--配置DRUID数据源 --> 28 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 29 <property name="driverClassName" value="${jdbc.driver}"></property> 30 <property name="url" value="${jdbc.url}"></property> 31 <property name="username" value="${jdbc.username}"></property> 32 <property name="password" value="${jdbc.password}"></property> 33 </bean> 34 </beans>
@Con?guration: 表明这个类是配置类
@ComponentScan:组件包扫描
@Bean:修饰方法,会执行工厂方法,并把返回的对象放到IOC容器中
@PropertySource 读取属性文件的注解
@Import 导入其它的配置
总结:实际开发中是xml和注解混合配置,自定义的bean对象推荐使用注解,因为简单方便,而第三方或框架自带的类推荐使用xml来进行配置
1 主配置类 2 package com.hwua.config; 3 import java.beans.PropertyVetoException; 4 import javax.annotation.Resource; 5 import javax.sql.DataSource; 6 import org.apache.commons.dbutils.QueryRunner; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.beans.factory.annotation.Value; 9 import org.springframework.context.annotation.Bean; 10 import org.springframework.context.annotation.ComponentScan; 11 import org.springframework.context.annotation.Configuration; 12 import org.springframework.context.annotation.Import; 13 import org.springframework.context.annotation.PropertySource; 14 import com.mchange.v2.c3p0.ComboPooledDataSource; 15 /** 16 * 配置类的作用就等同于配置文件 17 * @author Administrator 18 * 19 */ 20 @Configuration 21 @ComponentScan(basePackages= {"com.hwua.service","com.hwua.dao"}) 22 @PropertySource("classpath:db.properties") 23 @Import(JDBCConfiguration.class)//导入其它配置类 24 public class SpringConfiguration { 25 26 //使用工厂方法去创建一个QueryRunner对象,工厂方法中的参数会自动从IOC容器中找到相应的对象进行 27 自动注入 28 @Bean("runner") 29 public QueryRunner createQueryRunner(@Autowired DataSource ds) { 30 return new QueryRunner(ds); 31 } 32 33 }
34 从配置类 35 package com.hwua.config; 36 import java.beans.PropertyVetoException; 37 import javax.sql.DataSource; 38 import org.springframework.beans.factory.annotation.Value; 39 import org.springframework.context.annotation.Bean; 40 import org.springframework.context.annotation.Configuration; 41 import com.mchange.v2.c3p0.ComboPooledDataSource; 42 @Configuration 43 public class JDBCConfiguration { 44 @Value("${jdbc.driver}") 45 private String driver; 46 @Value("${jdbc.url}") 47 private String jdbcUrl; 48 @Value("${jdbc.username}") 49 private String username; 50 @Value("${jdbc.password}") 51 private String password; 52 @Bean("dataSource") 53 public DataSource createDataSource() throws PropertyVetoException { 54 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 55 dataSource.setDriverClass(driver); 56 dataSource.setJdbcUrl(jdbcUrl); 57 dataSource.setUser(username); 58 dataSource.setPassword(password); 59 return dataSource; 60 } 61 }
◆ 实现转账案例
◆ 发现案例中的问题:
◆ 一个业务方法中的多个功能都是在自己的连接对象上来单独开启事务的,所以多个独立的dao不能使用同一个事务来进行处理,导致转账数据不一致.
◆ 解决案例中的问题
◆ ThreadLocal :用来给当前线程上绑定连接对象,一个请求用的就是一个线程,那么只要多个dao从线程上获取绑定的连接对象就能进行统一的事务处理.
◆ 动态代理 : 作用:在类上没有修改其源码的情况下,通过代理对象来对其功能进行增强.
◆ jdk动态代理:对实现接口的对象来创建代理类对象
◆ cglib动态代理:对没有实现接口的对象,通过对其创建子类对象来实现代理
14.1 AOP概念
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
14.2 应用场景
日志记录,性能统计,安全控制,事务处理,异常处理等等。
14.3 AOP的优势
作用: 在运行期间,在不修改源码的前提下对已有方法进行功能增强
优势:代码的复用,提高开发效率维护方便
14.4 AOP常用术语
◆ joinPoint(连接点): 目标对象,所有可以被增强的方法。
◆ Advice(通知/增强):具体增强功能的类
◆ PointCut(切入点):目标对象的方法,将要被增强的具体的方法。
◆ Introduction(引入):声明某个方法或字段。(不用)
◆ Target(目标对象):被代理的对象,也就是要被增强功能的哪个对象
◆ AOP 代理(AOp Proxy) Spring 帮我们创建的代理类对象
◆ Weaving(织入):将通知应用到切入点的过程。
◆ Aspect(切面):切入点+通知的组合。
14.5 通知(advise)的类型
◆ 前置通知[Before advice] 在业务方法执行之前执行的增强功能
◆ 后置通知[After returning advice]:在业务方法执行之后执行的增强功能
◆ 异常通知[After throwing advice]:在业务方法报错时要执行的增强功能
◆ 最终通知[After (?nally) advice]:在业务方法执行后,不管有没有异常,最终都要执行的增强功能
◆ 环绕通知[Around advice]:环绕通知围绕在切入点前后,比如一个方法调用的前后。这是最强大的通知类型,
◆ 可以手动通过代码来控制通知的类型.
步骤:
◆ 把通知类对象放到Spring容器中
◆ 使用aop:con?g标签来开始aop的配置
◆ 使用aop:aspect标签来配置切面
◆ id 属性随意给个名字
◆ ref: 引用的是通知类对象的id
◆ 使用aop:xxx标签来配置通知类型
◆ method 指的是通知类对象中具体执行的增强方法
◆ pointcut 指定具体的切入点,要编写切入点表达式,使用切入点表达式,必须要导入AspectJ的jar包
手动配置一个通知类(具有增强功能的类)
1 package com.hwua.advise; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.*; 5 import org.springframework.stereotype.Component; 6 7 /** 8 * 通知类,含有增强功能的一个类 9 * @author Administrator 10 * 11 */ 12 @Component("log") 13 @Aspect 14 public class LogAdvise { 15 @Pointcut("execution(* *..*.*(..))") 16 public void p1(){ 17 18 } 19 //具体要增强的功能 20 // @Before("p1()") 21 public void logBefore() { 22 System.out.println("日志开始记录...."); 23 } 24 // @AfterReturning("p1()") 25 public void logAfterRturning() { 26 System.out.println("日志开始结束...."); 27 } 28 // @AfterThrowing("p1()") 29 public void logAfterThrowing() { 30 System.out.println("日志记录错误...."); 31 } 32 // @After("p1()") 33 public void logAfter() { 34 System.out.println("关闭日志...."); 35 } 36 @Around("p1()") 37 public Object logRound(ProceedingJoinPoint proceedingJoinPoint){ 38 Object o = null; 39 Object[] args = proceedingJoinPoint.getArgs(); //获取业务方法中的参数列表 40 try { 41 logBefore(); 42 o = proceedingJoinPoint.proceed(args);// 手动的去指定业务对象 43 logAfterRturning(); 44 } catch (Throwable throwable) { 45 logAfterThrowing(); 46 throwable.printStackTrace(); 47 }finally { 48 logAfter(); 49 } 50 // System.out.println("环绕通知...."); 51 return o; 52 } 53 }
包含要被增强的方法的类(业务类)
1 package com.hwua.service.impl; 2 3 import com.hwua.service.StudentService; 4 import org.springframework.stereotype.Component; 5 6 @Component("studentService") 7 public class StudentServiceImpl implements StudentService { 8 9 @Override 10 public void saveStudent() throws Exception { 11 System.out.println("添加学生...."); 12 13 } 14 15 @Override 16 public void delStudent(Integer id) throws Exception { 17 System.out.println("删除学生...."); 18 19 } 20 21 @Override 22 public void updateStudent() throws Exception { 23 System.out.println("更新学生...."); 24 // int a = 1/0; 25 26 } 27 28 @Override 29 public void findStudentById(Integer id) throws Exception { 30 System.out.println("查询学生...."); 31 } 32 33 }
语法: [访问修饰符] 返回类型 包名.包名...类名.方法名(参数1,参数2)
- 返回类型可以使用通配符*,代表返回任意类型
- 包名可以使用通配符*, 包名随意*.*.* *.*.. ..代表任意的子包
- 类名可以使用通配符*,代表任意类
- 方法名可以使用通配符,代表任意方法
- 参数可以使用.. 代表任意多个参数(0到多)
void com.hwua.service.impl.StudentServiceImpl.saveStudent()
常规写法: * com.hwua.service.impl.StudentServiceImpl.*(..)
<?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: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.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <context:component-scan base-package="com.hwua"/> <!-- 配置通知类对象 --> <bean id="log" class="com.hwua.advise.LogAdvise"/> <bean id="stuService" class="com.hwua.service.impl.StudentServiceImpl"/> <!--开始配置aop --> <aop:config> <!-- 配置全局切入点,这个切入点可以被当前所有前面中的通知使用 --> <aop:pointcut expression="execution(* *..*.*(..))" id="p1"/> <!--配置一个切面 --> <aop:aspect id="logAdvise" ref="log"> <!-- 配置局部切入点,这个切入点只能给当前界面的通知使用 --> <!-- <aop:pointcut expression="execution(* *..*.*(..))" id="p1"/> --> <!--<aop:before method="logBefore" pointcut-ref="p1"/> <aop:after-returning method="logAfterRturning" pointcut-ref="p1"/> <aop:after-throwing method="logAfterThrowing" pointcut-ref="p1"/> <aop:after method="logAfter" pointcut-ref="p1"/>--> <aop:around method="logRound" pointcut-ref="p1"/> </aop:aspect> </aop:config> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
◆ aop:before 配置前置通知
◆ aop:after-returning 配置后置通知
◆ aop:after-throwing 配置异常通知
◆ aop:after 配置最终通知
◆ aop:around 配置环绕通知:通过手动编写代码来实现业务的功能加强.就是可以手动来进行设置
◆ 配置了环绕通知后,在执行的时候默认不执行业务方法,Spring框架为我们提供了一个接口:ProceedingJoinPoint,当通知中的方法被执行的时候,Spring会把传过来 ProceedingJoinPoint类型的一个对象,里面包含了业务方法的相关信息
1 package com.hwua.utils; 2 import java.sql.SQLException; 3 import org.aspectj.lang.annotation.After; 4 import org.aspectj.lang.annotation.AfterReturning; 5 import org.aspectj.lang.annotation.AfterThrowing; 6 import org.aspectj.lang.annotation.Aspect; 7 import org.aspectj.lang.annotation.Before; 8 import org.aspectj.lang.annotation.Pointcut; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.stereotype.Component; 11 /** 12 * 事务管理器 简单的说就要要对业务方法增强的事务功能 13 * @author Administrator 14 */ 15 @Component("txManager") 16 @Aspect//切面类 17 public class TXManager { 18 @Pointcut("execution(* com.hwua.service.impl.AccountServiceImpl.*(..))") 19 private void p1() { 20 } 21 22 @Autowired 23 private ConnectionUtils connectionUtils = null; 24 public void setConnectionUtils(ConnectionUtils connectionUtils) { 25 this.connectionUtils = connectionUtils; 26 } 27 //开启事务 28 @Before("p1()") 29 public void beginTransAction() { 30 System.out.println("前置通知"); 31 try { 32 connectionUtils.getConnection().setAutoCommit(false);//开启事务 33 } catch (SQLException e) { 34 e.printStackTrace(); 35 } 36 } 37 38 //提交事务 39 @AfterReturning("p1()") 40 public void commit() { 41 System.out.println("后置通知"); 42 try { 43 connectionUtils.getConnection().commit();//提交事务 44 } catch (SQLException e) { 45 e.printStackTrace(); 46 } 47 } 48 49 //回滚事务 50 @AfterThrowing("p1()") 51 public void rollback() { 52 System.out.println("异常通知"); 53 try { 54 connectionUtils.getConnection().rollback();//回滚事务 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } 58 } 59 60 //释放连接 61 @After("p1()") 62 public void release() { 63 System.out.println("最终通知"); 64 try { 65 connectionUtils.getConnection().close();//关闭连接 66 connectionUtils.release();//把连接对象从当前线程解绑 67 } catch (SQLException e) { 68 e.printStackTrace(); 69 } 70 }
注意点:使用注解配置AOP会出现执行顺序的问题,先执行前置通知,最终通知,(后置通知或异常通知)
使用注解配置AOP我们推荐使用配置环绕通知.
1 <!--开启AOP注解配置的支持 -->
2 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
事务管理器
1 package com.hwua.utils; 2 import java.sql.SQLException; 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.After; 5 import org.aspectj.lang.annotation.AfterReturning; 6 import org.aspectj.lang.annotation.AfterThrowing; 7 import org.aspectj.lang.annotation.Around; 8 import org.aspectj.lang.annotation.Aspect; 9 import org.aspectj.lang.annotation.Before; 10 import org.aspectj.lang.annotation.Pointcut; 11 import org.springframework.beans.factory.annotation.Autowired; 12 import org.springframework.stereotype.Component; 13 /** 14 * 事务管理器 简单的说就要要对业务方法增强的事务功能 15 * 16 * @author Administrator 17 * 18 */ 19 @Component("txManager") 20 @Aspect//切面类 21 public class TXManager { 22 @Pointcut("execution(* com.hwua.service.impl.AccountServiceImpl.*(..))") 23 private void p1() { 24 } 25 26 @Autowired 27 private ConnectionUtils connectionUtils = null; 28 public void setConnectionUtils(ConnectionUtils connectionUtils) { 29 this.connectionUtils = connectionUtils; 30 } 31 //开启事务 32 /*@Before("p1()")*/ 33 public void beginTransAction() { 34 System.out.println("前置通知"); 35 try { 36 connectionUtils.getConnection().setAutoCommit(false);//开启事务 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 } 40 } 41 42 //提交事务 43 /*@AfterReturning("p1()")*/ 44 public void commit() { 45 System.out.println("后置通知"); 46 try { 47 connectionUtils.getConnection().commit();//提交事务 48 } catch (SQLException e) { 49 e.printStackTrace(); 50 } 51 } 52 53 //回滚事务 54 /*@AfterThrowing("p1()")*/ 55 public void rollback() { 56 System.out.println("异常通知"); 57 try { 58 connectionUtils.getConnection().rollback();//回滚事务 59 } catch (SQLException e) { 60 e.printStackTrace(); 61 } 62 } 63 64 //释放连接 65 /*@After("p1()")*/ 66 public void release() { 67 System.out.println("最终通知"); 68 try { 69 connectionUtils.getConnection().close();;//关闭连接 70 connectionUtils.release();//把连接对象从当前线程解绑 71 } catch (SQLException e) { 72 e.printStackTrace(); 73 } 74 } 75 @Around("p1()") 76 public Object around(ProceedingJoinPoint pjp) { 77 Object obj=null; 78 Object[] args = pjp.getArgs();//获取业务方法的参数 79 try { 80 beginTransAction(); 81 obj=pjp.proceed(args);//业务方法 82 commit(); 83 } catch (Throwable e) { 84 rollback(); 85 e.printStackTrace(); 86 }finally { 87 release(); 88 } 89 return obj; 90 } 91 }
19.1 事务四大特性(ACID)
◆ 原子性:强调事务操作的单元是一个不可分割的整体.
◆ 一致性:事务操作前后数据要保持一致
◆ 隔离性:一个事务在执行的过程中,不应该受其它事务的影响
◆ 持久性:事务一旦提交,数据就永久持久化到数据库中,不能回滚
19.2在不考虑隔离性的情况下,事务操作引发的安全性问题
◆ 脏读:一个事务读取到另一个事务未提交的数据
◆ 不可重复读:一个事务读取到另一个已提交事务的update数据,导致多次读取数据产生不一致
◆ 幻读:一个事务读取到另一个已提交事务的insert数据,导致多次读取数据产生不一致.
19.3可以设置数据库的隔离级别来解决上面问题
◆ 读未提交(Read Uncommited):脏读,不可重复读,幻读,都避免不了
◆ 读已提交(Read committed):解决脏读,(不可重复读,幻读解决不了)
◆ 可重复读(Repeatable read):解决脏读,不可重复读,(幻读解决不了)
◆ 串行化(serializable):解决上述三个问题,效率比较低,会导致一个失去就等待另一个事务处理完毕.
19.4 Mysql事务隔离级别的设置和查询
1.查看数据库的隔离级别: select @@transaction_isolation;
2.设置数据库隔离级别: set session transaction isolation level 隔离级别
◆ 导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
◆ 配置spring自带的事务管理器对象
<!--配置事务管理器对象 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
◆ 配置一个事务通知 并 对事务通知进行属性的设置
isolation: 设置事务隔离级别
propagation: 事务的传播行为
- REQUIRED 必须要有事务,针对增删改的操作
- SUPPORTS 如果当前有事务则加入,如果没有则不用事务。
read-only="true" 代表查询
rollback-for: 指定碰到相应的异常就回滚事务,不配默认就是碰到异常就回滚
no-rollback-for: 指定碰到相应的异常不回滚事务,不配默认就是碰到异常就回滚
timeout:不设置就代表默认-1永不超时,设置数字单位是秒
<!--配置一个事务通知-->
<tx:advice id="txAdvise" transaction-manager="transactionManager">
<!--配置事务的属性 -->
<tx:attributes>
<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" />
<tx:method name="query*" isolation="DEFAULT" propagation="SUPPORTS"
read-only="true"/>
</tx:attributes>
</tx:advice>
◆ 配置切面
<aop:config> <!--配置切入点 --> <aop:pointcut expression="execution(*com.hwua.service.impl.AccountServiceImpl.*(..))" id="p1"/> <!--把通知切入到指定的切入点 --> <aop:advisor advice-ref="txAdvise" pointcut-ref="p1"/> </aop:config>
1. 开启事务的注解支持
<!--开启事务注解的支持 -->
<tx:annotation-driven/>
2. 在指定方法上设置事务处理@Transactional
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
课堂练习: 修改银行转账代码:
Spring 整合 jdbcTemplate实现声明式事务事务处理
Spring 整合 MyBatis来实现声明式事务处理
1. 下载spring整合web应用程序的jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.7.RELEASE</version> </dependency>
2. 我们去注册一个监听器去监听Servlet应用加载,只要监听到加载,我们就应该加载配置文件来创建容器
<!--配置全局参数 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
3. Servlet对象是在Servlet容器中,而我们创建的业务层,数据访问层对象都放在了IOC容器中,也就是不同容器间不能直接访问.我们可以使用一个工具类来得到
IOC容器的引用
ApplicationContext context=null;
@Override
public void init() throws ServletException {
//创建了IOC容器的引用
context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
//取IOC容器中bean对象
UserService us = context.getBean("userService", UserService.class);
标签:测试的 产生 下载地址 自动注入 eth 可重复 ssr 维护 Servle
原文地址:https://www.cnblogs.com/wzming0730/p/11044750.html