1.Spring
1.1 简介
Spring ->春天,为开源软件带来春天
2002,首次退出了Spring框架的雏形:interface21框架
Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
Spring的历年:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有技术框架!
SSH:Strut2 + Spring + Hibernate(全自动持久化框架)!
SSM:SpringMVC + Spring + MyBatis(半自动持久化框架,可自定义性质更强)
spring官网: https://spring.io/projects/spring-framework#overview 官方下载:https://repo.spring.io/release/org/springframework/spring/ GitHub: https://github.com/spring-projects/spring-framework Spring Web MVC: https://mvnrepository.com/artifact/org.springframework/spring-webmvc/5.2.7.RELEASE
Spring Web MVC 和 Spring-JDBC的pom配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 <!-- https: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.7.RELEASE</version> </dependency> <!-- https: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.7.RELEASE</version> </dependency>
1.2 优点
Spring是一个开源的免费框架(容器)!
Spring是一个轻量级的、非入侵式的框架!
控制反转(IOC),面向切面编程(AOP)
支持事务处理,对框架整合的支持!(几乎市面上所有热门的框架都能整合进去)!
Spring就是一个轻量级的控制反转(IoC)和面向切面编程(AOP)的框架 1.3 组成
核心容器(SpringCore) 核心容器提供Spring框架的基本功能。spring以bean的方式组织和管理Java应用的各个组件及其关系,spring使用BeanFactory来产生和管理Bean,是工厂模式的实现,BeanFactory使用控制反转(IoC)模式将应用的配置和依赖性规范与实际的应用程序代码分开
应用上下文(Spring Context)
Spring上下文是一个配置文件,向spring提供上下文信息,spring上下文包括企业服务
Spring面向切面编程(Spring AOP) AOP(Aspect Oriented Programming)通过配置管理特性,SpringAOP模块直接将面向方法的编程功能集成在了Spring框架中,Spring管理的任何对象都支持AOP,SpringAOP模块基于Spring的应用程序中的对象提供了事务管理服务,通过使用SpringAOP,不用依赖EJB组件,就可以将声明性事务管理集成在应用程序中
JDBC和DAO模块(Spring DAO) Dao(Data Access Object) JDBC、DAO的抽象层,提供了有意义的异常层次结构实现,可用该结构来管理异常处理,和不同数据库提供商抛出的错误信息,异常层次结构简化了错误处理,并且极大的降低了需要编写的代码数量,比如打开和关闭链接。
对象实体映射(Spring ORM) ORM(Object Relational Mapping) Spring插入了若干个ORM框架,提供了ORM对象的关系工具,其中包括Hibernate,JDO和IBatisSQL Map等,所有这些都遵从Spring的通用事务和DAO异常层次结构
Web模块(Spring Web) web上下文模块建立应用程序上下文模块之上,基于web的应用程序提供了上下文,所以spring框架支持与Struts集成,web模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作
MVC模块(SpringWebMVC) MVC(Model View Controller) MVC框架是一个全功能的构建Web应用程序的MVC实现,通过策略接口,MVC框架编程高度可配置的,MVC容纳了大量视图技术,其中包括JSP,POI等,模型由JavaBean来构成,存放于m当中,而视图是一个接口,负责实现模型,控制器表示逻辑代码,由c的事情。spring框架的功能可以用在任何J2EE服务器当中,大多数功能也适用于不受管理的环境,spring的核心要点就是支持不绑定到特定J2EE服务的可重用业务和数据的访问对象,毫无疑问这样的对象可以在不同的J2EE环境,独立应用程序和测试环境之间重用
1.4 扩展
现代化的java开发 -> 基于Spring的开发!
Spring Boot 一个快速开发的脚手架 基于SpringBoot可以快速开发单个微服务 约定大于配置!
Spring Cloud SpringCloud是基于SpringBoot实现的! 因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
2 .IoC(控制反转)理论指导 2.1 传统的调用 1.UserDao
1 2 3 4 package dao;public interface UserDao { void getUser () ; }
2.UserDaoImpl
1 2 3 4 5 6 package dao;public class UserDaoImpl implements UserDao { public void getUser () { System.out.println("默认获取用户数据" ); } }
3.UserService
1 2 3 4 package Service;public interface UserService { void getUser () ; }
4.UserServiceImpl
1 2 3 4 5 6 7 8 9 10 package Service;import dao.UserDao;import dao.UserDaoImpl;public class UserServiceImpl implements UserService { UserDao userDao = new UserDaoImpl(); public void getUser () { userDao.getUser(); } }
测试:
1 2 3 4 5 6 7 8 9 10 11 package holle0;import Service.UserService;import Service.UserServiceImpl;public class MyTest0 { public static void main (String[] args) { UserService userService = new UserServiceImpl(); userService.getUser(); } }
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
需要手动去new UserServiceImpl()
2.2 改进 我们使用一个Set接口实现。已经发生了革命性的变化!
1 2 3 4 5 6 7 8 private UserDao userDao;public void setUserDao (UserDao userDao) { this .userDao = userDao; }
set() 方法实际上是动态改变了 UserDao userDao 的 初始化部分(new UserDaoImpl()) ((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
本质上解决了问题,程序员不用再去管理对象的创建,系统的耦合性大大降低,可以更专注在业务的实现上
这是IoC(控制反转)的原型,反转(理解):主动权交给了用户
注:这里的用户实际上是使用代码的人,不是不写代码的客户
使用IOC:
2.3 IOC本质 控制反转 IOC(Inversion of Control)是一种程序设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法。没有IOC的程序中,我们使用面向对象编程,对象的创建于对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
3. HelloSpring pom中引入依赖
1 2 3 4 5 6 <!-- https: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.7.RELEASE</version> </dependency>
Hello:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package com.zjc.pojo;public class Hello { private String str; public String getStr () { return str; } public void setStr (String str) { this .str = str; } @Override public String toString () { return "Hello{" + "str='" + str + '\'' + '}' ; } }
beans.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd" > <!--在Spring中创建对象,在Spring这些都称为bean 类型 变量名 = new 类型(); Holle holle = new Holle(); bean = 对象(holle) id = 变量名(holle) class = new 的对象(new Holle();) property 相当于给对象中的属性设值,让str="Spring" --> <bean id="hello" class ="com.kaung.pojo.Hello" > <property name="str" value="Spring" /> </bean> </beans>
测试类MyTest:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import pojo.Hello;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest { public static void main (String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml" ); Hello holle = (Hello) context.getBean("hello" ); System.out.println(holle.toString()); } }
ClassPathXmlApplicationContext继承树(ctrl+h)
ClassPathXmlApplicationContext继承接口实现类(Ctrl+Alt+u)
通俗理解: 原来这套程序是:你写好菜单买好菜,客人来了自己把菜炒好招待,就相当于你请人吃饭 现在这套程序是:你告诉楼下餐厅,你要哪些菜,客人来的时候,餐厅把做好的你需要的菜送上来 IoC:炒菜这件事,不再由你自己来做,而是委托给了第三方__餐厅来做
此时的区别就是,如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来
4. IoC创建对象的方式 方式一:使用无参构造创建对象(默认) 方式二:使用有参构造创建对象:下面介绍 实体类User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.spring.pojo;public class User { public User () { } public User (String name) { this .name = name; } @Override public String toString () { return "User{" + "name='" + name + '\'' + '}' ; } public String getName () { return name; } public void setName (String name) { this .name = name; } String name; }
直接通过参数名(掌握)
1 2 3 4 <bean id="user" class ="pojo.User" > <constructor-arg name="name" value="zjc"></constructor-arg> </bean> <!-- 比如参数名是name,则有name="具体值" -->
总结:在配置文件加载的时候,容器(< bean>)中管理的对象就已经初始化了
5. Spring配置 5.1 别名 1 2 3 4 5 6 7 8 <bean id="user" class ="pojo.User" > <constructor-arg name="name" value="chen"></constructor-arg> </bean> <alias name="user" alias="userLove" /> <!-- 使用时 User user2 = (User) context.getBean("userLove" ); -->
5.2 Bean的配置 1 2 3 4 5 6 7 8 9 <!--id:bean的唯一标识符,也就是相当于我们学的对象名 class :bean 对象所对应的会限定名:包名+类型name :也是别名,而且name 可以同时取多个别名 --><bean id ="user" class ="pojo.User" name="u1 u2,u3;u4" > <property name="name" value="chen" /> </bean> <!-- 使用时 User user2 = (User) context.getBean("u1" ); -->
name里面的分隔符可以是:空格 逗号 分号等
5.3 import import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利 用import将所有人的beans.xml合并为一个总的!
张三(beans.xm1)
李四(beans2.xm1)
王五(beans3.xm1)
applicationContext.xml
1 2 3 <import resource="beans.xm1" /> <import resource="beans2.xml" /> <import resource="beans3.xm1" />
使用的时候,直接使用总的配置就可以了 注:按照在总的xml中的导入顺序来进行创建,后导入的会重写先导入的,最终实例化的对象会是后导入xml中的那个
6 依赖注入(DI)
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入
6.1 构造器注入 参考4. Ioc创建对象的方式
6.2 set方式注入【重点】 6.2.1创建Student类 与 Address类 Address类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Address { private String address; public String getAddress () { return address; } public void setAddress (String address) { this .address = address; } @Override public String toString () { return "Address{" + "address='" + address + '\'' + '}' ; } }
Student类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 package com.kuang.pojo;import java.util.*;public class Student { private String name; private Address address; private String[] books; private List<String> hobbies; private Map<String, String> card; private Set<String> game; private Properties infor; private String wife; public String getName () { return name; } public void setName (String name) { this .name = name; } public Address getAddress () { return address; } public void setAddress (Address address) { this .address = address; } public String[] getBooks() { return books; } public void setBooks (String[] books) { this .books = books; } public List<String> getHobbies () { return hobbies; } public void setHobbies (List<String> hobbies) { this .hobbies = hobbies; } public Map<String, String> getCard () { return card; } public void setCard (Map<String, String> card) { this .card = card; } public Set<String> getGame () { return game; } public void setGame (Set<String> game) { this .game = game; } public Properties getInfor () { return infor; } public void setInfor (Properties infor) { this .infor = infor; } public String getWife () { return wife; } public void setWife (String wife) { this .wife = wife; } @Override public String toString () { return "Student{" +"\n" + "name='" + name + '\'' +"\n" + ", address=" + address.toString() +"\n" + ", books=" + Arrays.toString(books) +"\n" + ", hobbies=" + hobbies +"\n" + ", card=" + card +"\n" + ", game=" + game +"\n" + ", infor=" + infor +"\n" + ", wife='" + wife + '\'' +"\n" + '}' ; } }
6.2.2 配置beans.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id="address" class ="com.kuang.pojo.Address" > <property name="address" value="啦啦啦" /> </bean> <bean id="student" class ="com.kuang.pojo.Student" > <!--第一种,普通值注入 --> <property name="name" value="name你好" /> <!--第二种,ref注入 --> <property name="address" ref="address" /> <!--数组注入 --> <property name="books" > <array> <value>三国</value> <value>西游</value> <value>水浒</value> </array> </property> <!--list列表注入 --> <property name="hobbies" > <list> <value>唱</value> <value>跳</value> <value>rap</value> <value>篮球</value> </list> </property> <!--map键值对注入 --> <property name="card" > <map> <entry key="username" value="root" /> <entry key="password" value="root" /> </map> </property> <!--set(可去重)注入 --> <property name="game" > <set> <value>wangzhe</value> <value>lol</value> <value>galname</value> </set> </property> <!--空指针null 注入 --> <property name="wife" > <null></null> </property> <!--properties常量注入 --> <property name="infor" > <props> <prop key="id">20200802</prop> <prop key="name">cbh</prop> </props> </property> </bean> </beans>
其中 array list set 均为value单闭合标签 map与props比较特殊单独记忆
6.2.3 测试 1 2 3 4 5 6 7 8 9 10 11 import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import pojo.Student;public class MyTest { public static void main (String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml" ); Student stu = (Student) context.getBean("student" ); System.out.println(stu.toString()); } }
6.3 拓展注入 使用p c命名空间
User类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.kuang.pojo;public class User { private String name; private int id; public User () { } public User (String name, int id) { super (); this .name = name; this .id = id; } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getId () { return id; } public void setId (int id) { this .id = id; } @Override public String toString () { return "User [name=" + name + ", id=" + id + "]" ; } }
使用p和c命名空间需要导入xml约束
xmlns:p=“http://www.springframework.org/schema/p” xmlns:c=“http://www.springframework.org/schema/c”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ?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" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd" > <!--p命名空间注入/set注入,需要存在无参构造函数和对应的set方法 相当于 property--> <bean id="user" class ="pojo.User" p:name="cxk" p:id="20" > </bean> <!--c命名空间,通过构造器注入,需要存在相应的构造函数 相当于 construct-args --> <bean id="user2" class="pojo.User" c:name="cbh" c:id="22"></bean> </beans>
可以理解为:c->construct-args p->propertyg
官方解释为:
6 Bean作用域
只需要知道【单例模式】和【原型模式】就可以了 其余的request、session、application这些只能在web开放中使用!
6.1 单例模式 默认就是单例模式
1 <bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="singleton"></bean>
6.2原型模式 每次从容器中get的时候,都产生一个新对象!
1 <bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="prototype"></bean>
7. Bean的自动装配 自动装配是Spring满足bean依赖的一种方式 Spring会在上下文自动寻找,并自动给bean装配属性 在Spring中有三种装配的方式
在xml中显示配置
在java中显示配置
隐式的自动装配bean 【重要】
环境搭建:一个人有两个宠物
byType自动装配:byType会自动查找,和自己对象set方法参数的类型相同的bean
保证所有的class唯一(类为全局唯一)[如果没有set方法不会提示]
byName自动装配:byName会自动查找,和自己对象set对应的值对应的id
保证所有id唯一,并且和set注入的值一致[如果没有set方法不会提示]
1 2 3 4 <!-- 找不到id和多个相同class --> <bean id ="cat1" class ="pojo.Cat" /><bean id="cat2" class ="pojo.Cat" /> <!-- 找不到 id=cat,且有两个Cat -->
7.1 测试自动装配 pojo的Cat类
1 2 3 4 5 public class Cat { public void shut () { System.out.println("miao" ); } }
pojo的Dog类
1 2 3 4 5 6 public class Dog { public void shut () { System.out.println("wow" ); } }
pojo的People类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package pojo;public class People { private Cat cat; private Dog dog; private String name; public Cat getCat () { return cat; } public void setCat (Cat cat) { this .cat = cat; } public Dog getDog () { return dog; } public void setDog (Dog dog) { this .dog = dog; } public String getName () { return name; } public void setName (String name) { this .name = name; } @Override public String toString () { return "People{" + "cat=" + cat + ", dog=" + dog + ", name='" + name + '\'' + '}' ; } }
xml配置 ->byType 自动装配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id="cat" class ="pojo.Cat" /> <bean id="dog" class ="pojo.Dog" /> <!--byType会在容器自动查找,和自己对象属性相同的bean 例如,Dog dog; 那么就会查找pojo的Dog类,再进行自动装配 --> <bean id="people" class ="pojo.People" autowire="byType" > <property name="name" value="cbh"></property> </bean> </beans>
xml配置 ->byName 自动装配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd" ><bean id="cat" class ="pojo.Cat" /> <bean id="dog" class ="pojo.Dog" /> <!--byname会在容器自动查找,和自己对象set方法的set后面的值对应的id 例如:setDog(),取set后面的字符作为id,则要id = dog 才可以进行自动装配 --> <bean id="people" class ="pojo.People" autowire="byName" > <property name="name" value="cbh"></property> </bean> </beans>
byName只能匹配到小写
7.2 使用注解实现自动装配 1.导入context约束:xmlns:context=”http://www.springframework.org/schema/context"
2.配置注解的支持:< context:annotation-config/>
1 2 3 4 5 6 7 8 9 10 11 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd" > <context:annotation-config/> </beans>
7.2.1 @Autowired 默认是byType方式,如果匹配不上,就会byName 在属性上个使用,也可以在set上使用 我们可以不用编写set方法了,前提是自动装配的属性在Spring容器里,且要符合ByName 自动装配
1 2 3 4 5 6 7 public class People { @Autowired private Cat cat; @Autowired private Dog dog; private String name; }
beans.xml文件
Autowire源码
1 2 3 public @interface Autowired { boolean required () default true ; }
如果定义了Autowire的require属性为false,说明这个对象可以为null,否则不允许为空(false表示找不到装配时不抛出异常)默认为true。
7.2.2 @Autowired+@Qualifier @Autowired不能唯一装配时,需要@Autowired+@Qualifier
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候,可以使用@Qualifier(value = “dog”)去配合使用,指定一个唯一的id对象
1 2 3 4 5 6 7 8 public class People { @Autowired private Cat cat; @Autowired @Qualifier (value = "dog" ) private Dog dog; private String name; }
如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找
7.2.3 @Resource 默认是byName方式,如果匹配不上,就会byType
1 2 3 4 5 6 7 public class People { Resource(name="cat" ) private Cat cat; Resource(name="dog" ) private Dog dog; private String name; }
Autowired是byType,@Autowired+@Qualifier = byType && byName
Autowired是先byteType,如果唯一則注入,否则byName查找。 resource是先byname,不符合再继续byType
7.2.4 @Autowired 与 @Resource的区别
都是用来自动装配的,都可以放在属性字段上
@Autowired通过byType的方式实现,而且必须要求这个对象存在!(require默认为true)【常用】
@Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
执行顺序不同:@Autowired默认通过byType的方式实现。@Resource默认通过byname的方式实现
8. 使用注解开发 在spring4之后,使用注解开发,必须要保证aop包的导入
使用注解需要导入contex的约束
1 2 3 4 5 6 7 8 9 10 11 12 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd" > <context:annotation-config/> </beans>
8.1 bean 有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。
1 2 3 4 <!--指定要扫描的包,这个包下面的注解才会生效 别只扫一个com.kuang.pojo包[范围如果大的话能覆盖到里面的包]--> <context:component-scan base-package ="com.kuang" /> <context:annotation-config/>
1 2 3 4 5 6 @Component public class User { public String name ="zjc" ; }
@Component :组件,放在类上,说明这个类被spring管理了,这就是bean。
8.2 属性注入@Value 1 2 3 4 5 6 7 8 9 10 11 12 @Component public class User { @Value ("kuangshen" ) public String name; public void setName (String name) { this .name = name; } }
8.3 衍生的注解 @Component有几个衍生注解,会按照web开发中,按照mvc三层架构分层。
dao (@Repository)
service(@Service)
controller(@Controller)
这四个注解的功能是一样的,都是代表将某个类注册到容器中
8.4 自动装配置 @Autowired:默认是byType方式,如果匹配不上,就会byName
@Nullable:字段标记了这个注解,说明该字段可以为空
@Resource:默认是byName方式,如果匹配不上,就会byType
8.5、作用域@Scope 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Component @Scope ("prototype" )public class User { @Value ("kuangshen" ) public String name; @Value ("kuangshen" ) public void setName (String name) { this .name = name; } }
8.6、小结 xml与注解:
xml更加万能,维护简单,适用于任何场合
注解,不是自己的类使用不了,维护复杂
最佳实践:
xml用来管理bean
注解只用来完成属性的注入
要开启注解支持
9 .使用java的方式配置Spring 不使用Spring的xml配置,完全交给java来做! Spring的一个子项目,在spring4之后,它成为了核心功能
实体类User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class User { private String name; public String getName () { return name; } @value ("QINJIANG') public void setName(String name) { this.name = name; } @Override public String toString() { return " user{" + " name='" + name + ' \'' + '}' ; } }
配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class KuangConfig { public User getUser () { return new User(); } }
使用方式:
手动注册: @Bean
1 2 3 4 @Bean public User getUser () { return new User(); }
这个方法的名字,就相当于bean 标签中的 id 属性 ->getUser 这个方法的返同值,就相当于bean 标签中的class 属性 ->User
自动注入:@ComponentScan、@Component
先开启扫描:@ComponentScan(“com.Kuang.pojo”) //开启扫描 然后给相应实体类加上注解@Component
测试类
1 2 3 4 5 6 7 8 public class MyTest { public static void main (String[ ] args) { ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.Class); User getUser =(User)context.getBean( "getUser" ); System.out.Println(getUser.getName()); } }
10. 代理模式 为什么要学习代理模式,因为这就是SpringAOP的底层。
代理模式的分类:
10.1 静态代理
接口:
1 2 3 public interface Rent { public void rent () ; }
真实角色:
1 2 3 4 5 6 7 package pojo;public class HostMaster implements Host { public void rent () { System.out.println("房东要出租房子" ); } }
代理角色:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class Proxy implements Rent { public HostMaster host; public Proxy () { } public Proxy (HostMaster host) { super (); this .host = host; } public void rent () { seeHouse(); host.rent(); fee(); sign(); } public void seeHouse () { System.out.println("看房子" ); } public void fee () { System.out.println("收中介费" ); } public void sign () { System.out.println("签合同" ); } }
4.客户访问代理角色
1 2 3 4 5 6 7 8 9 10 11 12 13 public class Client { public static void main (String[] args) { HostMaster host = new HostMaster(); Proxy proxy = new Proxy(host); proxy.rent(); } }
聊聊aop:
10.2 动态代理 动态代理和静态代理角色一样,动态代理底层是反射机制
动态代理类是动态生成的,不是我们直接写好的!
动态代理(两大类):基于接口,基于类
基于接口:JDK的动态代理
基于类:cglib
java字节码实现:javasisit
了解两个类 1、Proxy:代理 2、InvocationHandler:调用处理程序
1.抽象角色
1 2 3 4 public interface Host { public void rent () ; }
2.真实角色
1 2 3 4 5 public class HostMaster implements Host { public void rent () { System.out.println("房东要租房子" ); } }
3.代理角色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class ProxyInvocationHandler implements InvocationHandler { private Rent rent; public void setRent (Rent rent) { this .rent = rent; } public Object getProxy () { return Proxy.newProxyInstance(this .getClass().getClassLoader(), rent.getClass().getInterfaces(),this ); } public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(rent, args); seeHose(); fee(); return result; } public void seeHose () { System.out.println("中介带着看房子!" ); } public void fee () { System.out.println("中介收取费用!" ); } }
4.用户类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class Client { public static void main (String[] args) { Host host = new Host(); ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.setRent(host); Rent proxy = (Rent) pih.getProxy(); proxy.rent(); } }
在此,我们可以提炼出ProxyInvocationHandler作为工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public class ProxyInvocationHandler implements InvocationHandler { private Object target; public void setTarget (Object target) { this .target = target; } public Object getProxy () { return Proxy.newProxyInstance(this .getClass().getClassLoader(), target.getClass().getInterfaces(),this ); } public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { log(method.getName()); Object result = method.invoke(target, args); return result; } public void log (String msg) { System.out.println("[Debug] 使用了一个" +msg+"方法" ); } }
动态代理的好处:
可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
公共角色就交给代理角色!实现了业务的分工!
公共业务发生扩展的时候,方便集中管理!
一个动态代理类代理的是一个接口,一般就是对应的一类业务
一个动态代理类可以代理多个类,只要是实现了同一个接口即可!
11、AOP 11.1 什么是AOP AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2 AOP在Spring中的作用 提供声明式事务;允许用户自定义切面
横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等… 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。 目标(Target):被通知对象。 代理(Proxy):向目标对象应用通知之后创建的对象。 切入点(PointCut):切面通知执行的“地点”的定义。 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即AOP在不改变原有代码的情况下,去增加新的功能。
11.3 使用Spring实现AOP 【重点】使用AOP织入,需要导入一个依赖包!
1 2 3 4 5 6 <!-- https: <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
方式一: 使用Spring的API接口【主要是SpringAPI接口实现】
在service包下,定义UserService业务接口和UserServiceImpl实现类
1 2 3 4 5 6 public interface UserService { public void add () ; public void delete () ; public void update () ; public void select () ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class UserServiceImpl implements UserService { public void add () { System.out.println("增加了一个用户!" ); } public void delete () { System.out.println("删除了一个用户!" ); } public void update () { System.out.println("更新了一个用户!" ); } public void select () { System.out.println("查询了一个用户!" ); } }
2.在log包下,定义我们的增强类,一个Log前置增强和一个AfterLog后置增强类
1 2 3 4 5 6 7 8 9 public class Log implements MethodBeforeAdvice { public void before (Method method, Object[] agrs, Object target) throws Throwable { System.out.println(target.getClass().getName()+"的" +method.getName()+"被执行了" ); } }
1 2 3 4 5 6 7 public class AfterLog implements AfterReturningAdvice { public void afterReturning (Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("执行了" +method.getName()+"方法,返回结果为:" +returnValue); } }
3.最后去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束,配置applicationContext.xml文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <!--注册bean--> <bean id="userService" class ="com.kuang.service.UserServiceImpl" /> <bean id="log" class ="com.kuang.log.Log" /> <bean id="afterLog" class ="com.kuang.log.AfterLog" /> <!--方式一:使用原生Spring API接口--> <!--配置aop:需要导入aop的约束--> <aop:config> <!--切入点:expression:表达式,execution(要执行的位置!* * * * *)--> <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))" /> <!--执行环绕增加!--> <aop:advisor advice-ref="log" pointcut-ref="pointcut" /> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" /> </aop:config> </beans>
4.测试
1 2 3 4 5 6 7 8 9 10 11 public class MyTest { public static void main (String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" ); UserService userService = (UserService) context.getBean("userService" ); userService.add(); } }
方式二: 自定义类来实现AOP【主要是切面定义】
在diy包下定义自己的DiyPointCut切入类
1 2 3 4 5 6 7 8 9 public class DiyPointCut { public void before () { System.out.println("======方法执行前======" ); } public void after () { System.out.println("======方法执行后======" ); } }
2.去spring中配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 <!--方式二:自定义类--> <bean id="diy" class ="com.kuang.diy.DiyPointCut" /> <aop:config> <!--自定义切面,ref 要引用的类--> <aop:aspect ref="diy" > <!--切入点--> <aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))" /> <!--通知--> <aop:before method="before" pointcut-ref="point" /> <aop:after method="after" pointcut-ref="point" /> </aop:aspect> </aop:config>
3.测试
同上
方式三: 使用注解实现!
在diy包下定义注解实现的AnnotationPointCut增强类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 @Aspect public class AnnotationPointCut { @Before ("execution(* com.kuang.service.UserServiceImpl.*(..))" ) public void before () { System.out.println("====方法执行前====" ); } @After ("execution(* com.kuang.service.UserServiceImpl.*(..))" ) public void after () { System.out.println("====方法执行后====" ); } @Around ("execution(* com.kuang.service.UserServiceImpl.*(..))" ) public void around (ProceedingJoinPoint jp) throws Throwable { System.out.println("环绕前" ); Signature signature = jp.getSignature(); System.out.println("signature:" +signature); Object proceed = jp.proceed(); System.out.println("环绕后" ); System.out.println(proceed); } }
2.在Spring配置文件中,注册bean,并增加支持注解的配置。
1 2 3 4 <!--方式三:使用注解--> <bean id="annotationPointCut" class ="com.kuang.diy.AnnotationPointCut" /> <!--开启注解支持! JDK(默认是 proxy-target-class ="false" ) cglib(proxy-target-class ="true" )--> <aop:aspectj-autoproxy/>
12 .整合mybatis mybatis-spring官网:https://mybatis.org/spring/zh/ mybatis的配置流程:
编写实体类
编写核心配置文件
编写接口
编写Mapper.xmi
测试
12.1 mybatis-spring-方式一
编写数据源配置
sqISessionFactory
sqISessionTemplate(相当于sqISession)
需要给接口加实现类【new】
将自己写的实现类,注入到Spring中
测试!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <dependencies > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-webmvc</artifactId > <version > 5.2.7.RELEASE</version > </dependency > <dependency > <groupId > org.aspectj</groupId > <artifactId > aspectjweaver</artifactId > <version > 1.9.4</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-jdbc</artifactId > <version > 5.2.7.RELEASE</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.2</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 2.0.4</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.12</version > </dependency > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.12</version > </dependency > </dependencies > <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > </resources > </build >
1 2 3 4 5 6 7 8 import lombok.Data;@Data public class User { private int id; private String name; private String pwd; }
1 2 3 4 5 6 package mapper; import java.util.List; import pojo.User; public interface UserMapper { public List<User > getUser(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package mapper; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import pojo.User; public class UserMapperImpl implements UserMapper{ //我们的所有操作,在原来都使用sqlSession来执行,现在都使用SqlSessionTemplate; private SqlSessionTemplate sqlSessionTemplate; //此处set方法是为了在Spring配置文件中注入属性时使用 public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } public List<User > getUser() { UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class); return mapper.getUser(); } }
1 2 3 4 5 6 7 8 9 10 11 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.kuang.mapper.UserMapper" > <select id ="getUser" resultType ="com.kuang.pojo.User" > select * from mybatis.mybatis </select > </mapper >
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.xml(可以完全省略,在spring-dao中的sqlSessionFactory位置设置)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > <settings > <setting name ="logImpl" value ="STDOUT_LOGGING" /> </settings > <typeAliases > <package name ="pojo" /> </typeAliases > </configuration >
spring-dao.xml(代替之前的MybatisUtils工具类)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <?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:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <bean id ="datasource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name ="driverClassName" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql:///mybatis?useUnicode=true& characterEncoding=UTF-8& userSSL=false& serverTimezone=GMT%2B8" /> <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </bean > <bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" > <property name ="dataSource" ref ="datasource" /> <property name ="configLocation" value ="classpath:mybatis-config.xml" /> <property name ="mapperLocations" value ="classpath:com/kuang/mapper/*.xml" /> </bean > <bean id ="sqlSession" class ="org.mybatis.spring.SqlSessionTemplate" > <constructor-arg index ="0" ref ="sqlSessionFactory" /> </bean > <bean id ="userMapper" class ="com.kuang.mapper.UserMapperImpl" > <property name ="sqlSessionTemplate" ref ="sqlSession" /> </bean > </beans >
applicationContext.xml(导入spring-dao.xml)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?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:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <import resource ="spring-dao.xml" /> <bean id ="userMapper" class ="mapper.UserMapperImpl" > <property name ="sqlSessionTemplate" ref ="sqlSession" > </property > </bean > </beans >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import mapper.UserMapper;import pojo.User;public class MyTest { public static void main (String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" ); UserMapper userMapper = (UserMapper) context.getBean("userMapper" ); for (User user : userMapper.getUser()) { System.out.println(user); } } }
12.2 mybatis-spring-方式二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package mapper;import pojo.User;import org.apache.ibatis.session.SqlSession;import org.mybatis.spring.support.SqlSessionDaoSupport;import java.util.List;public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { public List<User> getUser () { SqlSession sqlSession = getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; return mapper.getUser(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <?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:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <bean id ="datasource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name ="driverClassName" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql:///mybatis?useUnicode=true& characterEncoding=UTF-8& userSSL=false& serverTimezone=GMT%2B8" /> <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </bean > <bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" > <property name ="dataSource" ref ="datasource" /> <property name ="configLocation" value ="classpath:mybatis-config.xml" /> <property name ="mapperLocations" value ="classpath:com/kuang/mapper/*.xml" /> </bean > <bean id ="sqlSession" class ="org.mybatis.spring.SqlSessionTemplate" > <constructor-arg index ="0" ref ="sqlSessionFactory" /> </bean > </beans >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?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:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <import resource ="spring-dao.xml" /> <bean id ="userMapper2" class ="mapper.UserMapperImpl2" > <property name ="sqlSessionFactory" ref ="sqlSessionFactory" > </property > </bean > </beans >
1 2 3 4 5 6 7 8 9 public class MyTest6 { public static void main (String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" ); UserMapper userMapper = (UserMapper) context.getBean("userMapper2" ); for (User user : userMapper.getUser()) { System.out.println(user); } } }
13. 声明式事务
把一组业务当成一个业务来做;要么都成功,要么都失败!
事务在项目开发中,十分的重要,涉及到数据的一致性问题
确保完整性和一致性
事务的ACID原则: 1,原子性(atomic),事务由一个或多个行为捆绑在一起构成,好像是一个单独的工作单元。原子性保证事务内的操作要么都发生,要么都不发生。假如所有的操作都成功了,那么事务是成功的。加入任何一个操作失败,那么事务会进行回滚。
2,一致性(consistent),一旦一个事务结束了,不管成功还是失败,系统所处的状态和它的业务规则是一致的。也就是说,数据应当不会被破坏。
3,隔离性(isolation),事务应当允许多名用户操作同一个数据,一个用户的操作不会和其他用户的操作相混淆。因此,事务必须是隔离的,防止并行读写同一个数据的情况发生。注意,隔离通常意味着要锁定数据库的表或行。
4,持久性(durable),一旦事务完成,事务的结果应当持久化。这样不管什么样的系统崩溃,它们都能幸免于难。
声明式事务
先导入jar包,并没有新增的依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 <dependencies > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-webmvc</artifactId > <version > 5.2.7.RELEASE</version > </dependency > <dependency > <groupId > org.aspectj</groupId > <artifactId > aspectjweaver</artifactId > <version > 1.9.4</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-jdbc</artifactId > <version > 5.2.7.RELEASE</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.2</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 2.0.4</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.12</version > </dependency > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.12</version > </dependency > </dependencies > <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > </resources > </build >
1 2 3 4 5 6 7 8 9 10 11 12 import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pwd; }
1 2 3 4 5 6 7 8 9 10 11 import java.util.List;import org.apache.ibatis.annotations.Param;import pojo.User;public interface UserMapper { public List<User> getUser () ; public int insertUser (User user) ; public int delUser (@Param("id" ) int id) ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import pojo.User;import org.apache.ibatis.session.SqlSession;import org.mybatis.spring.support.SqlSessionDaoSupport;import java.util.List;public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper { public List<User> getUser () { User user = new User(5 ,"你好" ,"ok" ); insertUser(user); delUser(5 ); SqlSession sqlSession = getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; return mapper.getUser(); } public int insertUser (User user) { return getSqlSession().getMapper(UserMapper.class ).insertUser (user ) ; } public int delUser (int id) { return getSqlSession().getMapper(UserMapper.class ).delUser (id ) ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.kuang.mapper.UserMapper" > <select id ="getUser" resultType ="user" > select * from mybatis.user </select > <insert id ="insertUser" parameterType ="user" > insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert > <delete id ="delUser" parameterType ="_int" > delete from mybatis.user where id = #{id} </delete > </mapper >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > <settings > <setting name ="logImpl" value ="STDOUT_LOGGING" /> </settings > <typeAliases > <package name ="pojo" /> </typeAliases > </configuration >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 <?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:aop ="http://www.springframework.org/schema/aop" xmlns:tx ="http://www.springframework.org/schema/tx" xsi:schemaLocation ="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <bean id ="datasource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name ="driverClassName" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql:///mybatis?useUnicode=true& characterEncoding=UTF-8& userSSL=false& serverTimezone=GMT%2B8" /> <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </bean > <bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" > <property name ="dataSource" ref ="datasource" /> <property name ="configLocation" value ="classpath:mybatis-config.xml" /> <property name ="mapperLocations" value ="classpath:com/kuang/mapper/*.xml" /> </bean > <bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <constructor-arg ref ="datasource" /> </bean > <tx:advice id ="txAdvice" transaction-manager ="transactionManager" > <tx:attributes > <tx:method name ="add" propagation ="REQUIRED" /> <tx:method name ="delete" propagation ="REQUIRED" /> <tx:method name ="update" propagation ="REQUIRED" /> <tx:method name ="query" read-only ="true" /> </tx:attributes > </tx:advice > <aop:config > <aop:pointcut id ="txpointcut" expression ="execution(* com.kuang.mapper.*.*(..))" /> <aop:advisor advice-ref ="txAdvice" pointcut-ref ="txpointcut" /> </aop:config > </beans >
Spring中七种Propagation类的事务属性详解:
REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择也是spring的默认选择。
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?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:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <import resource ="spring-dao.xml" /> <bean id ="userMapper" class ="mapper.UserMapperImpl" > <property name ="sqlSessionFactory" ref ="sqlSessionFactory" > </property > </bean > </beans >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import mapper.UserMapper;import pojo.User;public class MyTest { public static void main (String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" ); UserMapper userMapper = (UserMapper) context.getBean("userMapper" ); for (User user : userMapper.getUser()) { System.out.println(user); } } }
注意: UserMapperImpl中getUser()方法先插入一个user在删除一个user。 只有在同一次使用Sqlsession时事务才起作用。
上述文件主要看spring-dao最后那部分即可