介绍
Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 Spring
MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的 Java EE 企业应用开源框架。
历史
1997 年 IBM 提出了 EJB 的思想
1998 年, SUN 制定开发标准规范 EJB1.0
1999 年, EJB1.1 发布
2001 年, EJB2.0 发布
2003 年, EJB2.1 发布
2006 年, EJB3.0 发布
Rod Johnson(spring 之父)
Expert One-to-One J2EE Design and Development(2002)
阐述了 J2EE 使用 EJB 开发设计的优点及解决方案
Expert One-to-One J2EE Development without EJB(2004)
阐述了 J2EE 开发不使用 EJB 的解决方式(Spring 雏形)
2017 年 9 月份发布了 spring 的最新版本 spring 5.0 通用版(GA)
优势
方便解耦,简化开发
通过 Spring 提供的 IoC 容器,可以将对象间的依赖关系交由 Spring 进行控制,避免硬编码所造成的过度程序耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可
以更专注于上层的应用。
AOP 编程的支持
通过 Spring 的 AOP 功能,方便进行面向切面的编程,许多不容易用传统 OOP 实现的功能可以 通过 AOP 轻松应付。
声明式事务的支持
可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活的进行事务的管理,提高开发效率和质量。
方便程序的测试
可以用非容器依赖的编程方式进行几乎所有的测试工作,测试不再是昂贵的操作,而是随手可做的事情。
方便集成各种优秀框架
Spring 可以降低各种框架的使用难度,提供了对各种优秀框架( Struts、 Hibernate、 Hessian、 Quartz等)的直接支持。
降低 JavaEE API 的使用难度
Spring 对 JavaEE API(如 JDBC、 JavaMail、远程调用等)进行了薄薄的封装层,使这些 API 的使用难度大为降低。
Java 源码是经典学习范例
Spring 的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对 Java 设计模式灵活运用以及对 Java 技术的高深造诣。它的源代码无意是 Java 技术的最佳实践的范例。
体系
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SZLBNWce-1645684511387)(1 笔记.assets/image-20201207095130584.png)]
IoC 的概念和作用
什么是程序的耦合
耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。 耦合性存在于各个领域,而非软件设计中独有的,但是我们只讨论软件工程中的耦合。
在软件工程中, 耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。 软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。 划分模块的一个准则就是高内聚低耦合。
它有如下分类:
(1) 内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。
(2) 公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。
(3) 外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传递该全局变量的信息,则称之为外部耦合。
(4) 控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进行适当的动作,这种耦合被称为控制耦合。
(5) 标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间存在一个标记耦合。
(6) 数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。
(7) 非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实现的。
总结:
耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。
内聚与耦合
内聚标志一个模块内各个元素彼此结合的紧密程度,它是信息隐蔽和局部化概念的自然扩展。 内聚是从功能角度来度量模块内的联系,一个好的内聚模块应当恰好做一件事。它描述的是模块内的功能联系。耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或访问一个模块的点以及通过接口的数据。 程序讲究的是低耦合,高内聚。就是同一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却要不那么紧密。
内聚和耦合是密切相关的,同其他模块存在高耦合的模块意味着低内聚,而高内聚的模块意味着该模块同其他模块之间是低耦合。在进行软件设计时,应力争做到高内聚,低耦合
创建基础工程
1.导入基础jar文件
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency>
2.创建核心配置文件
<?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"> </beans>
3.创建bean
public class User { }
4.核心配置文件创建bean对象标签
<?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"> <!--空参构造--> <bean id="user" class="cn.laixueit.component.User"></bean> </beans>
5.测试获取bean对象
@Test public void testBean(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = context.getBean("user", User.class); user.show(); } @Test public void testBean2(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) context.getBean("user"); user.show(); }
IOC
实例化 Bean 的三种方式
第一种方式:使用默认无参构造函数
<!--空参构造--> <bean id="user" class="cn.laixueit.component.User"></bean> --java-- public class User { }
如果没有无参构造方法name就会创建失败
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MnD48pSU-1645684511388)(1 笔记.assets/image-20201208212145916.png)]
第二种方式: spring 管理静态工厂-使用静态工厂的方法创建对象
public class Service { public static User createService(){ return new User(); } }
<bean id="staticService" class="cn.laixueit.component.Service" factory-method="createService"></bean>
第三种方式: spring 管理实例工厂-使用实例工厂的方法创建对象
public class Dao { public User getInstance(){ return new User(); }
<bean id="dao" class="cn.laixueit.component.Dao"></bean> <bean id="userInstan" factory-bean="dao" factory-method="getInstance"></bean> @Test public void testService(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = context.getBean("staticService", User.class); user.show(); }
作用方位
作用:
用于配置对象让 spring 来创建的。
默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
属性:
id: 给对象在容器中提供一个唯一标识。用于获取对象。
class: 指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
scope: 指定对象的作用范围。
* singleton :默认值,单例的.
* prototype :多例的.
* request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
* session :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
* global session globalSession 相当于 session. :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么 作用范围/生命周期
init-method: 指定类中的初始化方法名称。
destroy-method: 指定类中销毁方法名称。单例对象: scope=“singleton”
一个应用只有一个对象的实例。它的作用范围就是整个引用。
生命周期:
对象出生:当应用加载,创建容器时,对象就被创建了。
对象活着:只要容器在,对象一直活着。
对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
多例对象: scope=“prototype”
每次访问对象时,都会重新创建对象实例。
生命周期:
对象出生:当使用对象时,创建新的对象实例。
对象活着:只要对象在使用中,就一直活着。
对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。<bean id="user" class="cn.laixueit.component.User" init-method="init" destroy-method="distyory">
销毁必须手动调用,因为main方法结束会结束线程,但是不能多例
DI
依赖注入的概念
依赖注入: Dependency Injection。 它是 spring 框架核心 ioc 的具体实现。
我们的程序在编写时, 通过控制反转, 把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。
ioc 解耦只是降低他们的依赖关系,但不会消除。 例如:我们的业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系, 在使用 spring 之后, 就让 spring 来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。注入的数据有三类
- 基本和string
- 其它bean类型
- 复杂类型和集合类型
注入的方式
- 构造注入
- set注入
- 注解注入
构造函数注入
package cn.laixueit; import java.util.Date; public class User { private String name; private int age; private Date birthday; public User(String name, int age, Date birthday) { this.name = name; this.age = age; this.birthday = birthday; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } }
<bean id="user" class="cn.laixueit.User"> <constructor-arg type="java.lang.String" value="test12"></constructor-arg> <constructor-arg index="1" value="123"></constructor-arg> <constructor-arg name="birthday" ref="now"></constructor-arg> </bean> <bean id="now" class="java.util.Date"></bean>
public void constructor(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); User user = (User) context.getBean("user"); System.out.println(user); }
优势
在创建对象的时候必须注入参数,不然对象无法创建
缺点
改变了bean的实例化方式,就算用不到也必须提供参数
set 方法注入
注意:注入的时候关注的是set的方法名,不是根据变量名注入
public class User { private String name; private int age; private Date birthday; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setBirthday(Date birthday) { this.birthday = birthday; }
<bean id="user" class="cn.laixueit.User"> <property name="name" value="托尔斯泰"></property> <property name="age" value="12"></property> <property name="birthday" ref="now"/> </bean> <bean id="now" class="java.util.Date"></bean>
使用 p 名称空间注入数据(本质还是调用 set 方法)
<?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:p="http://www.springframework.org/schema/p" --这里需要引入p命名空间 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="cn.laixueit.User" p:name="aaa" p:age="12" p:birthday-ref="now"> </bean> <bean id="now" class="java.util.Date"></bean>
注意:需要在头文件处引入命名空间
注入集合属性
顾名思义,就是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。
我们这里介绍注入数组, List,Set,Map,Properties。具体代码如下:private String[] names; private List lists; private Set sets; private Map map; ...省略set方法
<bean id="user" class="cn.laixueit.User"> <property name="names"> <array> <value>AAA</value> <value>bbb</value> <value>ccc</value> </array> </property> <property name="lists"> <list> <value>list1</value> <value>list2</value> <value>list3</value> </list> </property> <property name="sets"> <set> <value>set1</value> <value>set2</value> <value>set3</value> </set> </property> <property name="map"> <map> <entry value="aaa" key="aaa"></entry> <entry value="bbb" key="bbb"></entry> <entry value="ccc" key="ccc"></entry> </map> </property> </bean>
注意:set、list、数组,三种方式注入的标签可以互换,不需要对应,即set可以使用list,list可以使用array
基于注解的 IOC 配置
注解的分类
- 用于创建对象的类似于bean标签
@component @controller @service @repository
使用注解必须开启扫描
<?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 https://www.springframework.org/schema/context/spring-context.xsd"> <!--使用注解,必须开启扫描,通知spring扫描那些包--> <context:component-scan base-package="cn.laixueit"/> </beans>
<context:component-scan base-package=“cn.laixueit.controller,cn.laixueit.exceptioon”></context:component-scan>
可以存在多个注解扫描,也可以一次扫描多个包,使用逗号隔开
默认类名小写
- 用于注入数据的类似于property
@autowired:# 自动类型注入,只能注入bean类型,可以省略set方法 @Qualifier:# 自动类型注入基础上,安装bean的id进行注入,给自动注入不能单独使用,必须个@autowired一起使用,给方法注入参数,可以单独使用 : value:bean的id @resource:#按照bean的id注入,注入bean类型 : name:指定bean的id @value: 注入基本数据类型和String :value:用于指定值
@autowired
@Autowired private UserDao userDao;
会根据类型注入,如果同时存在两个相同类型的就会报错
例如:
两个类都实现了某一个接口
public interface UserDao { public void show(); } @Repository("a1") public class UserMapper implements UserDao{ public void show(){ System.out.println("dao...show..a1"); } } @Repository("a2") public class UserMapper2 implements UserDao{ public void show(){ System.out.println("dao...show..a2"); } } @Autowired private UserDao userDao;
这样直接注入类型就会报错
修改为如下,就不会报错,根据名称查找
@Autowired @Qualifier("a1") private UserDao userDao;
@resource就是上面两个标签的结合体,没给name救护根据类型,给了就是根据id找
- 用户改变作用范围的类似于scope
@scope:# 指定bean的作用方位 : value :作用范围,取值和xml配置一样
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE * @see ConfigurableBeanFactory#SCOPE_SINGLETON
- 生命周期的(了解)类似于init-method,destroy-method
@PostConstruct:初始化 @PreDestroy:指定销毁方法
spring5的新注解
对比
注解的优势: 配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。 XML 的优势: 修改时,不用改源码。不涉及重新编译和部署
Spring 整合 Junit
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext ac = new ClassPathXmlApplicationContext(“bean.xml”);
IAccountService as = ac.getBean(“accountService”,IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就无须手动创建了,问题也就解决了。
我们都知道, junit 单元测试的原理(在 web 阶段课程中讲过),但显然, junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在, junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。
这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了解决
- 导包
- 使用@runwith替代原有驱动器
- 使用@contextConfiguration指定spring核心配置文件位置
- 使用@autowired给测试类注入测试的bean
AOP 的相关概念
什么是AOP
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1HrT3kOv-1645684511388)(1 笔记.assets/image-20201209115222385.png)]
优势
在不修改源代码的情况下,对已有代码进行增强
减少重复代码
提高开发效率
维护方便
词汇
Joinpoint(连接点):
所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点。
Pointcut(切入点):
所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义Advice(通知/增强):
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
通知的类型: 前置通知,后置通知,异常通知,最终通知,环绕通知。
Introduction(引介):
引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field。
Target(目标对象):
代理的目标对象。
Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。
spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
Proxy(代理) :
一个类被 AOP 织入增强后,就产生一个结果代理类。
Aspect(切面):
是切入点和通知(引介)的结合
前置通知
后置通知
环绕通知
异常通知
xml配置AOP
aop需要导入的包
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.11.RELEASE</version> </dependency> </dependencies>
spring.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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="cn.laixueit"/> <!--配置切入点,和增强--> <aop:config> <!--切入点--> <aop:pointcut id="point" expression="execution(* cn.laixueit.service.UserService.add(..))"/> <!--切面 ref:引入切面bean的id --> <aop:aspect ref="logs"> <!--切面bean的增强方法--> <aop:before method="addLogBefor" pointcut-ref="point"></aop:before> <aop:after method="addLogAfter" pointcut-ref="point"></aop:after> <aop:after-throwing method="addLogThorw" pointcut-ref="point"></aop:after-throwing> // 封装目标方法,使其切入点的方法都换为这个 <aop:around method="addLogRound" pointcut-ref="point"></aop:around> </aop:aspect> </aop:config> </beans>
切面
package cn.laixueit.log; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.stereotype.Component; @Component public class Logs { public void addLogBefor(){ System.out.println("add..log...之前"); } public void addLogAfter(){ System.out.println("add..log...之后"); } public void addLogFinalize(){ System.out.println("add..log...最终"); } public void addLogThorw(){ System.out.println("add..log...异常出现通知"); } public void addLogRound(ProceedingJoinPoint pc) throws Throwable { System.out.println("add..log...环绕通知"); pc.proceed(); } }
注解配置AOP
1 导包
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.11.RELEASE</version> </dependency> </dependencies>
2 配置文件开启注解aop和扫描注解
<context:component-scan base-package="cn.laixueit"/> <aop:aspectj-autoproxy/>
3 在需要作为通知的类上加入注解
@Component @Aspect public class AOPLog { @Before("execution(* cn.laixueit.service.*.*(..))") public void before(){ System.out.println("before....."); } }
Spring 中的 JdbcTemplate
1.导包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.11.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.11.RELEASE</version> </dependency>
2.配置数据源
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="10"></property> <property name="maxStatements" value="100"></property> <property name="acquireIncrement" value="2"></property> </bean>
3.测试数据源
// IOC容器注⼊ @Autowired private DataSource dataSource; public void save() { try { String sql = "insert into t_dept(deptName) values('test');"; Connection con = null; Statement stmt = null; // 连接对象 con = dataSource.getConnection(); // 执⾏命令对象 stmt = con.createStatement(); // 执⾏ stmt.execute(sql); // 关闭 stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } }
4.注入jdbcTemplate
<!-- 2. 创建JdbcTemplate对象 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
5.使用jdbctemplate
//使⽤Spring的⾃动装配 @Autowired private JdbcTemplate template; @Override public void save() { String sql = "insert into user(name,password) values('zhoggucheng','123')"; template.update(sql); }
6.测试
@Test public void test33() { ApplicationContext ac = new ClassPathXmlApplicationContext("bb/bean.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.save(); }
package cn.test.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class TestDemo { @Autowired private JdbcTemplate jdbcTemplate; @Test public void insert(){ jdbcTemplate.execute("insert into user(user_name) values ('张三21')"); } @Test public void insert2(){ jdbcTemplate.update("insert into user(user_name) values (?)","aa"); } @Test public void del(){ jdbcTemplate.update("delete from user where id = ?",200108); } @Test public void update(){ jdbcTemplate.update("update user set user_name=? where id =?","aa",200107); } @Test public void query(){ List<User> userList = jdbcTemplate.query("select * from user", new UserMapper()); System.out.println(userList); } @Test public void queryone(){ List<User> userList = jdbcTemplate.query("select * from user where id =43", new UserMapper()); System.out.println(userList); } class UserMapper implements RowMapper<User>{ public User mapRow(ResultSet resultSet, int i) throws SQLException { User user = new User(); user.setId(resultSet.getInt("id")); user.setUserName(resultSet.getString("user_name")); return user; } } }
Spring 中的事务控制
1 XML配置
事务操作时针对数据库的,如果没有数据库操作,那么事务是无效的
- 导包
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.11.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
- 配置spring.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: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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="cn.laixueit"></context:component-scan> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="jdbc:mysql:///mybatis?serverTimezone=UTC"></property> <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property> </bean> <!--jdbc模板--> <bean id="jbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--事务通知--> <tx:advice id="interceptor" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" read-only="false" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--切面--> <aop:config> <aop:pointcut id="ponit" expression="execution(* cn.laixueit.service.*.*(..))"/> <aop:advisor advice-ref="interceptor" pointcut-ref="ponit"></aop:advisor> </aop:config> </beans>
- service层
package cn.laixueit.service; import cn.laixueit.dao.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserMapper userMapper; public void save(){ System.out.println("add....之前"); userMapper.save(); // int i = 1/0; System.out.println("add....之后"); } }
- dao层
package cn.laixueit.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class UserMapper { @Autowired private JdbcTemplate jdbcTemplate; public void save(){ System.out.println("save...ok"); jdbcTemplate.execute("insert into user(user_name) values ('张三21')"); } }
- 测试
package demo; import cn.laixueit.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml"}) public class TestDemo { @Autowired private UserService userService; @Test public void save(){ userService.save(); } }
2 注解方式的配置
<?xml version="1.0" encoding="UTF-8"?>
导包和xml一致(略)
spring.xml
<context:component-scan base-package=“cn.laixueit”></context:component-scan>
<!--事务管理器--> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--开启事务注解--> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> </beans>
a/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package=“cn.laixueit”></context:component-scan>
<!--事务管理器--> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--开启事务注解--> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> </beans>