Spring5

简介

spring是一个开源的免费的框架(容器)
spring是一个轻量级的,非入侵式的框架!
控制反转(IOC),面向切面变成(AOP)
支持事务的处理,对框架整合的支持
总结:spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!

2002年首推出了Spring框架的雏形:interface21框架
Spring框架以interface21框架为基础经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
spring框架的目的:就是解决企业应用开发的复杂性
spring理念:使现有的技术更加容易使用,本身就是一个大杂烩,整合了现有的技术框架
官网:

https://spring.io/projects/spring-framework#overview

官方下载地址:

https://repo.spring.io/release/org/springframework/spring/

要使用spring5框架首先就要导入依赖:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.5.RELEASE<ersion>
</dependency>

组成:

在这里插入图片描述

扩展:

现代的java开发其实就是spring的开发
在这里插入图片描述

  • Spring Boot
    • 是一个快速开发的脚手架,
    • 基于SpringBoot可以快速的开发单个微服务
    • 约定大于配置
  • SpringCloud
    • SpringCloud是基于SpringBoot实现的
      现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,就是需要完全掌握Spring以及SpringMVC!

IOC理论推导

1,UserDao接口

2,UserDaoImpl实现类

3,UserService业务接口

4,UserServiceImpl业务实现类

public class UserServiceImpl implements UserService{
    private UserDao userDao= new UserDaoXXXImpl();
    //注意,此处的UserDaoXXXImpl()代表不同的dao层实现类
    public void getUser() {
        userDao.getUser();
    }
}

controller层为:

public class Mytest {
    public static void main(String[] args) {
        //用户实际调用的是业务层,dao层他们不需要接触
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }
}

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码!
private UserDao userDao= new UserDaoImpl();
只能通过修改此处new不同的实现类来调用不同的Dao层实现类

如果程序的代码量十分庞大,修改一次的成本代价十分的昂贵
早期程序示意图:
在这里插入图片描述
我们可以在UserServiceImpl中使用一个set接口来实现,就已经发生了革命性的变化

private UserDao userDao;
//利用set进行动态实现值的注入
public  void setUserDao(UserDao userDao) {
   this.userDao = userDao;
}

测试代码变为:

public class Mytest {
    public static void main(String[] args) {
        //用户实际调用的是业务层,dao层他们不需要接触
        UserService userService = new UserServiceImpl();
       
        //通过在setUserDao(XXXX);中传入不同的对象,来实现不同的调用
        ((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
        
        userService.getUser();
    }
}

IOC实现示意图:
在这里插入图片描述
之前,程序是主动创建对象!控制权在程序猿手上(在UserServiceImpl层中进行控制调用)
使用了set注入之后,程序本身UserServiceImpl不再具有主动性,变成了被动的接收对象(接收控制层(测试代码)的参数)
这种思想从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低~可以更加专注在业务的实现上
这就是IOC的原型

IOC本质

所谓的IOC就是: 对象由Spring来创建管理装配
控制反转(IOC)是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法,没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,老秦认为所谓的控制反转就是:获取依赖对象的方式反转了
示意图:
在这里插入图片描述
采用XML的方式配置Bean的时候,Bean的定义信息和实现是分离的,而采用注解的方式可以把两者合二为一,
Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的
控制反转是一种通过描述(XML或者注解)并通过第三方去生产或获取特定对象的方式,
在Spring中实现控制反转的是IOC容器,它的实现方式就是依赖注入(DI)

Hello Spring

spring必备配置文件:
使用spring来创建对象在spring这些都称为Bean
Bean = 对象
这里就相当于Hello hello=new Hello()
Bean里面的id就相当于 变量(hello)
class = new 的对象;
property 相当于给对象中的属性设置一个值!
ref: 代表引用spring容器中已经创建好的对象
values:具体的值,基本数据类型

<?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="hello" class="com.xg.pojo.Hello">
        <property name="str" value="Spring"/>
        <!--你没看错,spring也是一种基本数据类型-->
    </bean>
</beans>

注意:
Hello对象是spring创建的

Hello对象的属性是由spring容器设置的

这个过程就叫做控制反转

传统应用程序的对象是由程序本身控制创建的,使用spring后对象是由spring创建的

反转: 程序本身不创建对象,而变成被动的接收对象

依赖注入:就是利用set方法来进行注入的

IOC是一种编程思想,由主动的编程变为被动的接收

可以通过new ClassPathXmlApplicationContext 查看一下底层源码

到现在我们不用再去程序中改动了,要实现不同的操作,只需要再xml配置文件中进行修改

所谓的IOC就是: 对象由Spring来创建管理装配
IOC的两种实现方式,BeanFactory和ApplicationContext,ApplicationContext是BeanFactory的一个子接口,提供了更多更强大的功能,BeanFactory加载配置文件时候不会创建对象,只有在使用的时候才会创建对象,而ApplicationContext在加载配置文件的时候就会创建对象
接下来做一个简单的小测试来进行IOC和spring的演示说明
首先新建一个接口UserDao,并写一个getUser方法,并分别由两个类继承并实现(这里只写一个)

public class UserDaoMysqlImpl implements UserDao {
    public void getUser() {
        System.out.println("Mysql获取用户数据");
    }
}

然后再次新建一个接口并写一个实现类:

public class UserServiceImpl implements UserService{

    //此处将Dao接口组合进来
    private UserDao userDao;

    //然后创建一个新的方法,利用set进行动态实现值的注入
    public  void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    //UserService接口自带方法
    public void getUserService() {
        userDao.getUser();
    }

}

注册的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
       https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="mysqlImpl" class="com.xg.dao.UserDaoMysqlImpl"></bean>
    <bean id="DaoImpl" class="com.xg.dao.UserDaoImpl"></bean>
    <bean id="UserServiceImpl" class="com.xg.service.UserServiceImpl">
<!--      ref:  代表引用spring容器中已经创建好的对象
          values:具体的值,基本数据类型
          此处就是用来传递参数的,传递给UserServiceImpl中的setUserDao
          然后如果想要改变控制层(也就是测试类)的输出结果,就只能在此处的xml配置文件中进行更改
          ref引用类型
-->
        <property name="userDao" ref="mysqlImpl"/>
    </bean>

</beans>

此处就是用来传递参数的,传递给UserServiceImpl中的setUserDao,然后如果想要改变控制层(也就是测试类)的输出结果,就只能在此处的xml配置文件中进行更改
测试类:

public class Mytest {
    public static void main(String[] args) {
        //获取ApplicationContext; 拿到spring的容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //拿到容器之后,需要什么就get什么
        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
        userServiceImpl.getUserService();
    }
}

输出: Mysql获取用户数据

IOC创建对象的方式

IOC默认使用无参的方式创建对象

读取xml配置文件的时候就已经创建好了

有参构造创建对象

1,下标赋值

<!--    第一种给有参构造赋值的方法:-->
    <bean id="user" class="com.xg.pojo.User">
<!--        index就是下标,value就是参数的具体值-->
        <constructor-arg index="0" value="健身"/>
    </bean>

2,类型赋值

<!--    可能有多个相同类型的参数,所以不建议使用-->
    <bean id="user" class="com.xg.pojo.User">
        <constructor-arg type="java.lang.String" value="hahahahaha"></constructor-arg>
    </bean>

3,参数名赋值

    <bean id="user" class="com.xg.pojo.User">
        <constructor-arg name="name" value="啊实打实的"/>
    </bean>

测试:在同一个bean中创建两个变量
在这里插入图片描述

设置带参构造:
在这里插入图片描述
测试代码:在这里插入图片描述
输出结果:
在这里插入图片描述
PS:
在配置文件加载的时候容器中所有管理的对象就已经被初始化了也就是说只需要创建一次就可以使用所有的对象了

spring配置

别名设置:

<!--    别名,没什么用-->
    <alias name="userT" alias="user2"></alias>

bean的配置:

<!--    id:bean的唯一标识符,也就相当于我们学的对象名
        class:代表bean对象所对应的全限定名  也就是包名加类名
        name:也是别名,而且name可以取多个别名,不同名字之间用逗号或则空格分开
-->
    <bean id="userT" class="com.xg.pojo.User" name="user3 sada,asdsa  AQWEQ,777">
        <constructor-arg name="name" value="ASDASDASD"/>
    </bean>

配置文件组合import:

import一般用于团队开发使用,可以将多个配置文件导入合并为一个
假设项目中有多个人进行开发,但是负责的类不同,不同的类需要注册在不同的bean中,可以使用import将所有人的beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

       <import resource="beans.xml"/>
</beans>

DI依赖注入

构造器注入:

前面已经讲过有参无参构造器注入的问题了

set方式注入:

依赖注入就是靠set注入:
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入
环境搭建:
1,复杂类型:

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

2,真实测试对象:

@Data
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobby;
    private Map<String,String> card;
    private Set<String> game;
    private String wife;
    private Properties info;
}

3,beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.xg.pojo.Student">
<!--        第一种,普通值注入,直接用value-->
        <property name="name" value="希哥"></property>
    </bean>
</beans>

4,获取bean赋值的结果测试:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
}

bean的各种类型值注入:(spring声明变量)

<bean id="address" class="com.xg.pojo.Address">
   <property name="address" value="郑州"/>
</bean>

<bean id="student" class="com.xg.pojo.Student">
   <!--        普通值注入,直接用value-->
   <property name="name" value="希哥"></property>
   <!-- bean引用注入,用ref-->
   <property name="address" ref="address"></property>
   <!--        数组注入,ref-->
   <property name="books">
      <array>
         <value>《百年孤独》</value>
         <value>《基督山伯爵》</value>
         <value>《汤姆索亚历险记》</value>
      </array>
   </property>
   <!--        list注入-->
   <property name="hobby">
      <list>
         <value>听歌</value>
         <value>读书</value>
         <value>写字</value>
         <value>女朋友</value>
      </list>
   </property>
   <!--        Map集合注入-->
   <property name="card">
      <map>
         <entry key="身份证" value="411325"/>
         <entry key="驾照" value="473400"/>
         <entry key="查搜集" value="13123"/>
      </map>
   </property>
   <!--        set集合注入-->
   <property name="game">
      <set>
         <value>LOL</value>
         <value>DNF</value>
      </set>
   </property>
   <!--        null注入-->
   <property name="wife">
      <null/>
   </property>
   <!--        properties注入-->
   <property name="info">
      <props>
         <!--   注意,此处key就是key value是尖括号中的数据-->
         <prop key="学号">473400</prop>
         <prop key="性别"></prop>
         <prop key="username">希哥</prop>
         <prop key="password">981216</prop>
      </props>
   </property>
</bean>

测试代码以及输出结果:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
        /*Student(
           name=希哥,
           address=com.xg.pojo.Address@47ef968d,
           books=[《百年孤独》, 《基督山伯爵》, 《汤姆索亚历险记》],
           hobby=[听歌, 读书, 写字, 女朋友],
           card={身份证=411325, 驾照=473400, 查搜集=13123},
           game=[LOL, DNF], wife=null,
           info={学号=473400, 性别=男, password=981216, username=希哥})*/
    }
}

拓展方式注入:(C/P命名空间注入)

利用c命名空间或者p命名空间也可以进行注入属性:

<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命名必须要有这句代码
       xmlns:c="http://www.springframework.org/schema/c"  --c命名必须要有这句代码
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间注入,可以直接注入属性的值,其实就是property声明变量,用来简化代码的-->
<bean id="user" class="com.xg.pojo.User" p:name="希哥" p:age="22"/>
<!--c命名空间注入,通过构造器注入construct-args 其实就是构造器注入然后声明变量-->
<bean id="user2" class="com.xg.pojo.User" c:age="18" c:name="小果果"/>
</beans>

spring官方文档注释:
在这里插入图片描述
测试代码:

@Test
public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
   User user = (User) context.getBean("user2");
   System.out.println(user);
}

注意:
p命名空间和c命名空间都不能直接使用,必须要导入xml头文件约束:

xmlns:p="http://www.springframework.org/schema/p" --p命名必须要有这句代码
xmlns:c="http://www.springframework.org/schema/c"  --c命名必须要有这句代码

bean的作用域:

六种作用域如图所示:
在这里插入图片描述
这里只对单例和原型模式进行说明,其他的暂时用不到
单例模式(spring默认机制) 单线程比较常用:

<bean id="user2" class="com.xg.pojo.User" c:age="18" c:name="小果果" scope="singleton"/>

原型模式:每次从容器中get的时候都会产生一个新对象 多线程常用

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

其余的 request,session,application 这些只能再web开发中使用到

bean的自动装配:(重点)

自动装配是spring满足bean依赖的一种方式
spring会在上下文中自动寻找并自动给bean装配赋值
在spring中有三种自动装配的方式:

  • 在xml中记性显式配置
  • 在java中显式配置
  • 隐式的自动装配bean(重要)
    测试:
    环境搭建:一个人有两个宠物(这里使用xml手动装配属性)
    <bean id="cat" class="com.xg.pojo.Cat"></bean>
    <bean id="dog" class="com.xg.pojo.Dog"></bean>

    <bean id="people" class="com.xg.pojo.people">
        <property name="name" value="希哥"></property>
        <property name="cat" ref="cat"></property>
        <property name="dog" ref="dog"></property>
    </bean>

总体就是猫狗都有一个shout方法,人有猫狗还有自己的name属性,都是private,然后get/set以及toString
测试代码:

public class MyTest {
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //为了保证类可以被直接返回,所以再添加上一个 people.class
        people p = context.getBean("people", people.class);
        p.getCat().shout();
        p.getDog().shout();
    }
}

ByName自动装配:

<!--    ByName 的原理就是会自动再容器上下文中查找和自己对象set方法后面的值对应的bean  id-->
    <bean id="people" class="com.xg.pojo.people" autowire="byName">
        <property name="name" value="希哥"></property>
    </bean>

ByType自动装配:

    <bean class="com.xg.pojo.Cat"></bean>
    <bean id="dog" class="com.xg.pojo.Dog"></bean>

<!--    ByType 的原理就是会自动再容器上下文中查找,和自己类型对应的bean  id-->
    <bean id="people" class="com.xg.pojo.people" autowire="byType">
        <property name="name" value="希哥"></property>
    </bean>

重点:
ByName的时候需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
ByType的时候需要保证所有bean的class(类型)唯一,并且这个bean需要和自动注入的属性的类型一致

注解实现自动装配:

jdk1.5版本开始支持注解 spring2.5开始支持注解
要想使用注解就需要:
导入约束:

xmlns:context="http://www.springframework.org/schema/context"

配置注解的支持 < context:annotation-config/>[重要]

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

默认通过byname的方式实现如果找不到名字,则通过bytype实现,如果两个都找不到,就会报错

直接在属性上使用即可,也可以在set’方法上使用

使用Autowired我们可以不用编写set方法,

前提是你这个自动装配的属性在IOC(spring)容器中存在,且符合名字bytype,是先按照bytype再按照byname

拓展:
@Nullable 字段标记了这个注解,说明这个字段可以为null

这里是Autowired的源码

public @interface Autowired {
    boolean required() default true; //默认为true
}

如果显示的定义了Autowired的required = false,说明这个对象可以为null,否则不允许为null

@Autowired(required = false)

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解完成的时候,我们可以使用@Qualifier(value=“XXX”)去配置@Autowired的使用,指定一个唯一的bean对象注入

public class people {

    //如果显示的定义了Autowired的required = false,说明这个对象可以为null,否则不允许为null
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    @Qualifier(value="dog222")
    private Dog dog;
    private String name;
}
@Resource注解

默认通过byname的方式实现如果找不到名字,则通过bytype实现,如果两个都找不到,就会报错

    @Resource(name = "cat2")//如果有多个name,也可以添加括号,并声明使用具体哪一个
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;
两者区别:

@Resource和@Autowired的区别:

两者都是用来自动装配的,都可以放在属性字段上,两者都可以即通过byname,也可以通过bytype

但是两者的默认执行顺序不同:

@Resource是默认通过byname的方式实现

@Autowired默认通过bytype方式实现

使用注解开发:

在spring4之后要使用注解开发的话,就需要保证aop包的导入了
在这里插入图片描述
使用注解需要导入context的约束,增加注解的支持

<?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>
注解注入属性
//这里的注释等价于<bean id="people" class="com.xg.pojo.people"/>
//@Component 就代表组件的意思
@Component
public class User {
    //这里的@Value相当于在bean中的value赋值,在set方法前使用效果一样
    @Value("希哥")
    public String name;
    
}

衍生注解:
@Component(万能注解)有几个衍生注解,我们在web开发中,会按照mvc三层架构分层

  • dao @Repository
  • service @Service
  • controller @Controller
    这四个注解功能都是一样的,都是将某个类注册到spring容器中,也就是装配bean

自动装配

  • -@Autowired:自动装配通过类型,姓名 如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)
  • -@Nullable 字段标记了这个注解,说明这个字段可以为null
  • -@Resurce 自动装配通过名字和类型

作用域

@Scope("singleton")//这里代表作用域使用单例模式
//prototype 代表原型模式,其他的还有,不过bean中配置有提醒,注解配置没有提醒
public class User {
    //这里的@Value相当于在bean中的value赋值,在set方法前使用效果一样
    @Value("希哥")
    public String name;
}

总结:

xml与注解:

  • xml更加万能,适用于任何场合,维护简单方便
  • 注解如果不是自己的类使用不了,维护相对复杂

xml与注解的最佳使用方法:

  • xml用来管理bean

  • 注解只用来完成属性的注入

    我们在使用的过程中,只需要注意一个问题:必须让注解生效,就必须开启对注解的支持:

    <context:annotation-config/>
<!--    指定要扫描的包,这个包下面的注解就会生效-->
    <context:component-scan base-package="com.xg"/>

JavaConfig配置spring

我们现在要完全不使用spring的xml配置了,全权交给java来做,之前javaConfig是spring的一个子项目,在spring4之后,它变成了核心功能
测试:
POJO:(set/get/tostring)

//这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
@Component
public class User {
    @Value("希哥")//注入值
    private String name;
}

java配置类:

@Configuration//这个也会被spring容器托管并注册到容器中,因为它源码中本来就有@Component
//@Configuration 代表这是一个配置类,就和我们之前看的beans.xml是一样得到的
@ComponentScan("com.xg.pojo")//这个注解代表扫描特定包,没扫描也可以一用
@Import(Config2.class)//这个注解用来将不同的配置类的配置引用过来合并在一起

public class Config {

    //注册一个bean,就相当于之前写的xml中的bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    //@Bean
    public User user(){
        return new User();//这里的return就代表返回要注入到bean的对象
    }
    //注意,这只是bean的一种声明方式,
    //第二种不用写@bean,在测试类中使用context.getBean("user");依然可以运行
}

测试类:

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方法去做,我们就只能通过AnnotationConfig上下文获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        User user = (User) context.getBean("user");//此处括号中的方法名必须对应java配置类中@Bean的方法
        //如果没有配置类中没有@Bean则选取变量名并首字母小写
        System.out.println(user.getName());
    }
}

这种纯java的配置方式在springBoot中随处可见
面试问题:
创建对象有哪几种方式?:
可以new对象,可以set传值,也可以走容器,往后springBoot中还有一种

代理模式:

代理模式就是springAOP的底层实现
代理模式分为静态代理和动态代理两种
示意图:
在这里插入图片描述

静态代理模式:

角色分析:
抽象的角色:一般会使用接口或者抽象类来解决
真实的角色:也就是被代理的角色
代理角色 : 代理真实的角色,代理真实角色后我们一般会做一些附属操作
客户: 访问代理对象的人
代码流程:
创建租房接口

//租房
public interface Rent租房接口 {
    public void rent();
}

创建真实角色,房东:

//房东
public class Host房东 implements Rent租房接口{
    public void rent() {
        System.out.println("房东把房子租给了你");
    }
}

创建代理角色,中介:(可以实现房东的方法,并且有房东的扩展方法:签合同,并有能针对用户的扩展方法:收黑钱)

public class Proxy中介 implements Rent租房接口{
    //优先使用组合,
    private Host房东 host;

    public Proxy中介() {
    }

    public Proxy中介(Host房东 host) {
        this.host = host;
    }

    public void rent() {
        seeHouse();
        money();
        hetong();
        host.rent();
    }
    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }
    //收中介费
    public void money(){
        System.out.println("收中介费");
    }
    //签租赁合同
    public void hetong(){
        System.out.println("签租赁合同");
    }
}

客户端访问代理角色:(租房的人)

public class Client旅客 {
    public static void main(String[] args) {
        //要租房子首先要告诉中介租哪一个房东的房子
        Host房东 host = new Host房东();
        //代理,中介帮房东租房子,但是会有一些附属操作
        Proxy中介 proxy = new Proxy中介(host);
        //你不用面对房东,直接找中介租房就可以
        proxy.rent();
    }
}

代理模式的好处:
可以使真实角色的操作更加纯粹,不用关注一些公共的业务,公共业务就专门交给代理角色,实现业务的分工
公共业务发生扩展的时候方便集中管理
代理模式的缺点:
一个真实角色就会产生一个代理角色,代码量回翻倍,开发量也就会降低

静态代理模式再理解:

静态代理的实际运用:
首先是server接口:(房子)

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}

然后就是实现类:(也就是房东)

//真实对象
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 query() {
        System.out.println("查询了一个用户");
    }
}

代理类:(中介,这里比房东多的就是增加了一个日志输出)

//需求就是给每一条命令增加一个日志输出
public class UserServiceProxy implements UserService {//实现基本类的接口
   //首先获得基本类
    UserServiceImpl userService;
   
    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
    public void add() {
        log("add");
        userService.add();
    }
    public void delete() {
        log("delete");
        userService.delete();
    }
    public void update() {
        log("update");
        userService.update();
    }
    public void query() {
        log("query");
        userService.update();
    }
    //日志方法
    public void log(String msg){
        System.out.println("使用了"+msg+"方法");
    }
}

最后是实现类:(也就是租户)

public class Client {
    public static void main(String[] args) {
        //首先创建实现接口的房东和中介
        UserServiceImpl userService = new UserServiceImpl();
        UserServiceProxy proxy = new UserServiceProxy();
        //再将房东传递给中介
        proxy.setUserService(userService);
        //让中介来实现方法
        proxy.add();
    }
}

静态模式总结及示意图:

示意图:
如图:按照原本的纵向开发,产品发布后如果想要扩展功能,那就可能会导致上下层都需要不同程度的改动,来进行适应,所以就需要横向开发,面向切面编程,针对单一层进行修改扩充,而实现原理就是代理模式
在这里插入图片描述
自我总结:
我觉得静态代理模式就是一个类似于增强器的实现,原本的类只需要实现基本的接口就可以,扩展方法就由代理类(增强器)来帮助实现,但是同样的,增强器必须要获得要增强的对象的基本功能(也就是接口),并且自身也需要实现初始类(set方法),然后再对该功能进行增强,而到了要使用功能的时候,只需要三点:
1,创建好要增强的对象
2,再创建好增强器
3,将要增强的对象传递给增强器,最后直接用增强器来实现基本的增强方法
就像老秦说的,代理模式避免了代码对公共部分的调用,起到了解耦并简化代码的作用
显而易见,在这里看来,初始类本身就实现好了功能,而到了代理类又将该功能重复了一遍,看起来更加麻烦,不如直接将代理类的功能在初始类中进行实现。
但是就像弹幕中说的那样,如果代理类的功能有一万行,那么如果这一万行代码都放在初始类的每个方法中,必定会导致代码臃肿不堪,难以维护

动态代理:

动态代理和静态代理角色一样
动态代理的代理类是动态生成的,不是我们直接写好的
动态代理分为两大类,基于接口的动态代理,和基于类的动态代理
基于接口—JDK动态代理
基于类: cglib
Java字节码实现:javassit实现,不过这个是基于Jboss服务器的,并不是Tomca
需要理解两个类: Proxy: 代理 InvocationHandler: 调用处理程序
代码如下: (租房接口和实现租房接口的房东与上面一样,所以忽略不写)

//代理类,等会会用这个类自动生成代理类(其实就是invoke来帮助执行)
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Rent租房接口 rent;

    public void setRent(Rent租房接口 rent) {
        this.rent = rent;
    }

//创建格式为:    Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
//            new Class<?>[] { Foo.class },
//            handler);

    //生成 代理类对象
    public  Object getProxy(){
        //这里的三个参数分别为:classloader(用来知道类在哪个位置),获取类实现的接口是哪一个,还有InvocationHandler
        //前两个利用反射获取,第三个因为本类已经实现了InvocationHandler接口,所以直接出入this
        //这里是一段死代码,需要更改的只有rent
        Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
                rent.getClass().getInterfaces(), this);
        return proxyInstance;
    }

    //处理代理实例,并返回结果,注意,这里是实现接口所必须重写的方法
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质,就是使用反射机制实现
        //反射就是基于类可以获得类的属性,方法,以及关联的内部构造(如配置信息),使用ClassLoad获取
        //此处的invoke优点蒙蔽,但好像就是本身定义的实现,其他功能的实现也是在此方中进行嵌套处理
        seeHouse();
        Object invoke = method.invoke(rent, args);
        money();
        return invoke;
    }
    public void seeHouse(){
        System.out.println("中介带你去看房");
    }

    public void money(){
        System.out.println("中介让你掏中介费");
    }
}

租户实现代码:

public class Client {
    public static void main(String[] args) {
        //真实角色
        Host房东 host=new Host房东();

        //代理角色:现在还没有,但是我们已经有了生成代理角色的类
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象
        //当调用代理类的方法时,会通过反射机制调用左边的invoke方法来进行实现
        //此处是代理类获得了房东对象
        pih.setRent(host);
        //注意,这里的proxy代理类就是动态生成的,我们并没有写,原代理类的执行交给了invoke
        Rent租房接口 proxy = (Rent租房接口) pih.getProxy();
        proxy.rent();
    }
}

动态代理的好处
可以使真实角色的操作更加纯粹!,不用去关注一些公共的业务
公共业务就专门交给代理角色,实现了业务的分工
公共业务发生扩展的时候方便集中管理
一个动态代理类代理的是一个接口,一般就是对应的一类业务
一个动态代理类可以代理多个类,只要是实现了同一个接口就行
PS: 下面的代码为优化demo02的动态代理模式(已经可以当作工具类来进行使用了)
动态代理类如下:

//代理类,等会会用这个类自动生成代理类(其实就是invoke来帮助执行)
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    //生成 代理类对象
    public  Object getProxy(){
        //这里的三个参数分别为:classloader(用来知道类在哪个位置),获取类实现的接口是哪一个,还有InvocationHandler
        //前两个利用反射获取,第三个因为本类已经实现了InvocationHandler接口,所以直接出入this
        //这里是一段死代码,需要更改的只有rent
        Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
        return proxyInstance;
    }

    //处理代理实例,并返回结果,  注意,这里是实现接口所必须重写的方法
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质,就是使用反射机制实现
        //此处的invoke优点蒙蔽,但好像就是本身定义的实现,其他功能的实现也是在此方中进行嵌套处理
        log(method.getName());//日志方法
        Object invoke = method.invoke(target, args);
        aaa();
        return invoke;
    }
    public void aaa(){
        System.out.println("哈哈哈哈");
    }
    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }
}

租户实现类"

//这里实现了demo02的接口及方法
public class Client {
    public static void main(String[] args) {
        //真实角色:房东
        UserService userService=new UserServiceImpl();
        //代理角色,这里用动态代理来进行
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //注意,这里只需要将要代理的对象作为参数传递进去
        //所以有其他的需要代理的对象就不用再像静态代理那样每一个对象都生成一个代理方法
        pih.setTarget(userService);//设置要代理的对象
        
        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();
        proxy.query();//这里调用了invoke方法
    }
}

AOP

定义:

AOP意为面向切面编程通过预编译的方式和运行期间动态代理实现编程功能的统一维护的一种技术,AOP是OOP的延续,是软件开发的一个热点,也是spring框架的一个重要内容,是函数式编程的一种衍生泛型,AOP可以对业务逻辑的各个部分进行隔离,从而使得业务各个部分之间的耦合度降低,提高程序的可重用行,同时提高了开发贷效率
在这里插入图片描述

AOP在spring中的作用

提供声明式事务:允许用户自定义切面
横切关注点:可以约定用用程序多个模块的方法或者功能,即使是与我们行为逻辑无关的,但是我们需要关注的部分就是横切关注点
比如日期,安全,缓存,事务等等

  • 切面(Aspect):横切关注点被模块化的特殊对象,其实就是一个类
  • 通知(Advice):切面必须要完成的工作,其实就是类的一个方法
  • 目标(Target):被通知的对象
  • 代理(Proxy):向目标对象应用通知之后创建的对象
  • 切入点(PointCut):切面通知执行的"地点"的定义
  • 连接点(JointPoint):与切入点匹配的执行点
    在这里插入图片描述
    SpringAOP中,通过Advice定义横切逻辑,Spring中支持五种类型的Advice
    在这里插入图片描述
    AOP也就是再不改变原有代码的情况下去增加新的功能实现

使用spring实现AOP

重点:使用AOP织入,必须要导入一个依赖包

xxxxxxxxxx5 1<dependency>2   <groupId>org.aspectj</groupId>3   <artifactId>aspectjweaver</artifactId>4   <version>1.9.4</version>5</dependency>
方法一:使用spring的API接口(主要springAPI接口实现)

接口:

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}

实现类:(代理模式钟的房东)

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 query() {
        System.out.println("查询了一个用户");
    }
}

前置方法:

public class log implements MethodBeforeAdvice {

    //参数解释:method: 代表要执行的目标对象的方法
    //objects:参数(组合)
    //o:目标对象
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

后置方法:

import java.lang.reflect.Method;
//这个接口是返回之后的afteradvice(可以拿到返回值),用返回之前afteradvice接口也可以
public class AfterLog implements AfterReturningAdvice {
    //returnValue 返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为"+returnValue);
    }
}

xml文件中配置bean并导入AOP约束

<?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">
    <!--  xmlns:aop是 aop:config导入的     
          并且注意上面中有两份,一份将beans改为aop-->
<!--    注册bean-->
    <bean id="userService" class="com.xg.service.UserServiceImpl"/>
    <bean id="log" class="com.xg.log.log"/>
    <bean id="after" class="com.xg.log.AfterLog"/>
<!--    方式一:使用原生的Spring API接口-->
<!--    配置AOP:需要导入AOP的约束-->
    <aop:config>
<!--        需要一个切入点:也就是我们需要在什么地方进行执行-->
<!--        这里需要一个expression表达式:execution(xxx),括号中写要执行的位置-->
<!--        这里第一个*代表要引出的位置,第二个*是通配符,代表类中所有的方法,紧接着的(..)代表可以有任意参数-->
        <aop:pointcut id="pointcut" expression="execution(* com.xg.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加,下面这句代码的意思就是将log类切入到上面一行指定id(也就是pointcut)代表的方法中,
            当然,也可以多个方法对应各个id或者多个方法对应同一id-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="after" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

测试代码:

public class MyTest {
    public static void main(String[] args) {
        //测试第一步,首先要获取classpath下的xml文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //注意:动态代理,代理的是接口,不是实现类
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}
方法二:自定义来实现AOP(主要是切面定义)

此方法与方式一的区别就是方式二单纯是为了切入通知,没有使用接口,也就无法获得参数,相当于简化版的方式一
插入的通知代码如下:

public class DiyPointCut {
    public void before(){
        System.out.println("==========方法执行前==========");
    }
    public void after(){
        System.out.println("==========方法执行后==========");
    }
}

xml配置文件如下:

<!--    方式二:自定义类-->
<!--    首先,同样也需要注册bean-->
    <bean id="diyclass" class="com.xg.DIY.DiyPointCut"/>
<!--    然后再进行配置-->
    <aop:config>
<!--        自定义切面,ref 要 引用的类-->
        <aop:aspect ref="diyclass">    主要比方式一多了这行代码
<!--            切入点-->
            <aop:pointcut id="point" expression="execution(* com.xg.service.UserServiceImpl.*(..))"/>
<!--            需要切入的通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

其他的则完全一致,包括测试代码(Spring的重点不在代码,而是在xml配置文件中)

方式三:使用注解实现

使用注解就更加简单了,XML配置文件如下:(proxy-target-class="false"完全可以不写,true和flase都一样可以实现)

<!--    方式三:使用注解来进行实现-->
    <bean id="AnnotationPointCut" class="com.xg.Annotation.AnnotationPointCut"/>
<!--    代理模式的执行有基于接口或者基于类两种方式
        基于接口就是JDK,基于类就是使用cglib实现
        默认就是使用JDK来进行实现(proxy-target-class="false"就代表默认使用JDK)
        proxy-target-class="true"就代表使用cglib
-->
<!--    此处代表开启注解支持!-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

通知类如下: (关于前后和环绕的优先级问题为环绕在前,然后按照先进先出原则)

//方式三,使用注解方式实现AOP
@Aspect//此注释用来标明此类事一个切面
public class AnnotationPointCut {
    @Before("execution(* com.xg.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }
    @After("execution(* com.xg.service.UserServiceImpl.*(..))")
    public void before2(){
        System.out.println("我上了一趟厕所");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取切入的点
    @Around("execution(* com.xg.service.UserServiceImpl.*(..))")
    //下面的参数代表获取连接点(见typora笔记)
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");//执行前的通知
        System.out.println(joinPoint.getSignature());//获取类的签名   Signature翻译过来就是签名
        //有下面这行代码才能执行切入点的方法
        Object proceed = joinPoint.proceed();//真正的执行
        System.out.println("环绕后");
    }
}

程序执行结果:
在这里插入图片描述

spring整合Mybatis

使用Mybatis的步骤:
1,导入相关jar包

  • junit
  • mybatis
  • MySQL数据库
  • Spring相关的
  • aop织入
  • mybatis-spring(new)
    2,编写测试文件
    3,测试

回忆mybatis

1,编写实体类
2,编写mybatis核心xml配置文件
3,编写接口(每一个接口一定要在mybatis核心配置文件中注册接口
4,编写Mapper.XML
5,测试

spring整合mybatis

操作步骤如下:(都在同一个xml配置文件spring-dao.xml中)
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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

编写数据源配置:

<!--DataSource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
    我们这里使用spring提供的jdbc:  org.springframework.jdbc.datasource.DriverManagerDataSource-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--        注意,这里所有的property name属性(url password)全部都是官方类写好的,并不是自定义的-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="981216"/>
    </bean>

编写sqlSessionFactory(死代码)

需要注意的是这里的property name=“dataSource”,后面ref的指向必须与上面数据源配置的id相同,两者之间是相互联系的

<!--    编写sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
<!--        绑定mybatis配置文件 configLocation就代表mybatis配置文件的地址 value的值中classpath:后面跟的就是文件地址-->
<!--        这样此处的spring-dao.xml就跟mybatis-config.xml连接起来了
        换句话说就是这里的spring配置信息(bean id="sqlSessionFactory")可以代替原本所需要的mybatis配置信息(mybatis-config.xml)-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--        下面这句代码就代表注册映射器-->
        <property name="mapperLocations" value="classpath:com/xg/mapper/UserMapper.xml"/>
<!--        <property name="typeAliases" value="com.xg.pojo.User"/>-->
    </bean>

<!--   SqlSessionTemplate:其实就是我们使用的sqlsession  Template翻译过来就代表模板,往后会经常遇到-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能使用构造器注入SqlSessionFactory  ,因为点开SqlSessionTemplate的源码就会发现它没有set方法
            没有set方法也就是没有办法注入SqlSessionFactory,进而利用SqlSessionFactory创建SqlSession创建对象-->
<!--        注意,下面这行的代码意思就是给第零个参数赋值,值也就是SqlSession-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

ps:这里的mybatis配置文件为:

<?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>
<!--    这里的typeAliases代表起别名-->
    <typeAliases>
        <package name="com.xg.pojo"/>
    </typeAliases>

<!--    <mappers>
        <mapper class="com.xg.mapper.UserMapper"/>
    </mappers>-->
</configuration>

UserMapper.xml配置文件为:

<?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.xg.mapper.UserMapper">
     <select id="selectUser" resultType="user">
         select * from mybatis.user;
     </select>
</mapper>

编写接口实现类并组合SqlSessionTemplate

import java.util.List;
//注意:使用spring实现mybatis多了这个实现类,是因为spring本身的东西接管对象之后自动创建,
//  而mybatis的本身的东西无法自动创建,只能手动创建一个set方法,
//  这个set方法本身就是原来mybatis要做的事情,这里将它作为一个业务层来做了(老秦原话)

//这里创建的是SqlSessionTemplate(也就是sqlsession模板)    注意,这里可以说就是service业务层的代码了
public class UserMapperImpl implements UserMapper {

    //在原来我们的所有操作都使用SqlSession来执行,现在都使用SqlSessionTemplate来执行
    private SqlSessionTemplate sqlSession;//这里直接使用组合的方法进行使用
    //这里就是将sqlsession注入到模板中,spring万物皆注入,注入的时候一定要给一个set方法,
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        //再最初mybatis的时候就是获取到sqlsession之后利用getmapper并传入接口对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //最后调用接口对象中的不同方法
        return mapper.selectUser();
    }
}

实现类注入到spring中

<!--    下面这行代码就是为了将userMapper类注入进spring配置文件中,并方便调用
      而调用这个类就是需要一个参数,也就是sqlSessionTemplate-->
    <bean id="userMapper" class="com.xg.mapper.UserMapperImpl">
       注意,这里的ref(属性引用)指向的是第二步中已经注册好的SqlSessionTemplate的id
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
<!--  接下来使用的方法就是在spring的xml注册文件中调用id为userMapper的配置信息,
      这个配置信息中已经包含了SqlSessionTemplate(也就是sqlsession模板),自然也就含有了sqlsession的一切功能
      比如UserMapper mapper = sqlSession.getMapper(UserMapper.class);然后调用接口对象中的不同方法
      如:mapper.selectUser();-->

测试使用:

public class mytest {
    @Test
    public void test() throws IOException {
/*      原mybatis的测试代码:  
        //首先获取xml配置文件的名称
        String resources ="mybatis-config.xml";
        //通过Resources.getResourceAsStream来获取名称对应配置文件
        //注意,一定要是ibatis包下面的
        InputStream in = Resources.getResourceAsStream(resources);
        //其次创建一个SqlSessionFactoryBuilder,并利用它的build方法来创建执行工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //最后利用执行工厂来执行,true代表默认提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }*/

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}

调优:

一般为了解耦,可以再创建一个新的xml配置文件(此处的名称就为applicationContext.xml),并将配置文件import到新的xnk配置文件中,这样就可以实现代码的细化分层,方便维护

<?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-dao.xml配置文件之后,原有的spring-dao配置文件就专注于操作数据库,并且不需要在进行更改了-->
    <import resource="spring-dao.xml"/>

    <bean id="userMapper" class="com.xg.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

spring整合mybatis简化版 (继承SqlSessionDaoSupport)

除了以下步骤,其他跟上一种方法一样:
UserMapperImpl实现类: 这里继承方法之后直接就可以getsqlsession来进行获取

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

对应的xml配置文件:

<!--    新的继承实现方法:  此方法省去了传递sqlSessionTemplate,只需要传入一个sqlSessionFactory参数,
        然后继承类会自动检测有没有sqlSessionTemplate,有了就算了,没有就创建一个新的sqlSessionTemplate-->
    <bean id="userMapper2" class="com.xg.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

对应的测试类:

    @Test
    public void SqlSessionDaoSupport(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        这里就是提取的另外注册的bean文件的id了
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }

总结:
对比可以发现第二种方法省去了注入sqlsession这一步骤,直接传递了sqlSessionFactory,
然后继承类接受到参数后自动创建一个sqlsession
相对于一种方法,该方法十分的简便,但是第一种的老方法必须要会使用,第二种方法并不重要,
因为往后还有更加简便的mybatis-pls方法,以及通用Mapper方法

PS:报错提示:

报错无法将属性“ sqlSessionTemplate”(bean的id)的类型“ java.lang.String”的属性值转换为所需的类型“ org.mybatis.spring.SqlSessionTemplate”;
原因: xml配置文件中bean的参数引用类型搞错了,要改为ref,而不是value
在这里插入图片描述
报错: class path resource [com/xg/mapper/UserMapper.xml] cannot be opened because it does not exist

类资源文件无法打开,因为它不存在,这点tmd可把老子害惨了,花了两天时间,之前mybatis的时候老秦就已经讲过这个问题了,说让建立xml配置文件的时候顺便就加上了,这次结果给忘了
解决方式:在xml配置文件中导入下列依赖

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

声明式事务

回顾事务

  • 把一组业务当成一个业务来做要么都成功,要么都失败
  • 事务在项目开发中十分的重要,设计到数据的一致性问题
  • 确保完整性和一致性

事务的ACID原则:

原子性

  • 一致性
  • 隔离性
    多个业务可能操作同一个资源,防止数据损坏,比如a借b钱,结果a的钱没少,但是b却借到了
  • 持久性
    事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器(数据库)中

自定义错误测试:

接口中创建以下方法:

public interface UserMapper {
    public List<User> selectUser();

    //添加一个用户
    int addUser(User user);
    //删除一个用户
    public int deleteUser(int id);
}

并在接口中实现:

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        User user = new User(5, "小王", "777777");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(5);
        return mapper.selectUser();
    }

    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

测试代码与之前的一样,就会发现代码执行报错,但是数据依然插入成功了,这就是个很严重的问题,也就需要事务来进行控制
错误的底层原理:
这其实是Innodb(因闹db)的底层原理: 除了死锁之外,事务都不会自动回滚

spring5事务管理(全是死代码)

声明式事务 :AOP 或者说叫做 交由容器管理事务
编程式事务: 需要在代码中进行事务的管理
注意: 要开启spring中的事务处理功能,必须要在spring中创建一个DataSourceTranactionManager对象:

<!--    配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="datasource"/>
      <!--或者参数配置为:
        <property name="dataSource" ref="datasource"/> 只要把参数传递进去就行了--> 
    </bean>

其他所需配置如下:

<!--结合AOP实现事务的植入-->
<!--    配置事务通知:-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        以下的代码是给那些方法配置事务-->
<!--        新知识:  配置事务的传播特性   propagation翻译过来就是传播-->
        <tx:attributes>
<!--            <tx:method name="add" />
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <tx:method name="query"/>-->
            <tx:method name="" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置事务的切入-->
    <aop:config>
<!--        切入点为mapper中所有类的所有方法-->
        <aop:pointcut id="txPointCut" expression="execution(*  com.xg.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

Spring中七种Propagation(传播)类的事务属性详解

REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。也是默认选择
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
ps:注意.这个配置将影响数据存储,必须根据情况选择。

为什么需要事务:

如果不配置事务,可能存在数据提交不一致的情况
如果我们不在spring中去配置声明式事务,我们就需要在代码中手动配置事务,
事务在项目的开发中十分的重要,涉及到数据的一致性和完整性问题,不容马虎

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值