狂神说 Spring5

1、Spring

1.1、简介

简介

Spring:春天——>给软件行业带来了春天
2002,首次推出了Spring框架的雏形:interface框架!
Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版
Rod Johnson,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
spring理念:使现有的技术更****加容易使用,本身是一个大杂烩。
SSH:Struct2 + 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: spring-webmvc最新版

复制代码
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.19</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.19</version>
</dependency>
复制代码

 1.2、优点

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

Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)编程的框架

1.3、组成

 

 

 1.4、扩展

现代化的java开发 -> 基于Spring的开发

 

  Spring Boot

  一个快速开发的脚手架。
  基于SpringBoot可以快速的开发单个微服务。
  约定大于配置。


Spring Cloud
  SpringCloud是基于SpringBoot实现的。
  因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!

弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”

2、IOC理论推导

  1.UserDao 接口 

package com.kuang.dao;

public interface UserDao {
    void getUser();
}
  1. UserDaoImp
package com.kuang.dao;

public class UserDaoImpl implements UserDao{
    public void getUser() {
        System.out.println("默认获取用户数据!");
    }
}
  1. UserSevice
package com.kuang.service;

public interface UserService {
    void getUser();
}
  1. UserServiceImp
复制代码
public class UserServiceImpl implements UserService{
    //调用Dao层,组合
    //方法写死,调用不同的dao接口需改变new对应方法
    private UserDao userDao= new UserDaoImpl();
@Override
public void getUser() { userDao.getUser(); } }
复制代码

测试:

复制代码
public class MyTest {

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

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!

 

 

 我们使用一个Set接口实现,已经发生了革命性的变化!

在Service层的实现类(UserServiceImpl)增加一个Set()方法
利用set动态实现值的注入!

复制代码
public class UserServiceImpl implements UserService{
    //调用Dao层,组合
    //方法写死,调用不同的dao接口需改变new对应的方法
    // private UserDao userDao= new UserDaoImpl();

    //优化:利用set进行动态实现值得注入
    private UserDao userDao;
    //alt+ins使用setter方法
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void getUser() {
        userDao.getUser();
    }
}
复制代码

set() 方法实际上是动态改变了 UserDao userDao 的 初始化部分(new UserDaoImpl())

测试中加上:

((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
  • 之前,程序是主动创建对象!控制权在程序猿手上!
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!

本质上解决了问题,程序员不用再去管理对象的创建

系统的耦合性大大降低,可以更专注在业务的实现上

这是IOC(控制反转)的原型,反转(理解):主动权交给了用户

 

 

 

 IOC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

 

 

 

 

 

 

 

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

 

3、HolleSpring

在父模块Pom.xml中导入jar包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.11.RELEASE</version>
</dependency>
  1. 新建一个maven项目,编写实体类  
复制代码
package com.kuang.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 + '\'' +
                '}';
    }
}
复制代码
  1. resources里编写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">


    <!--使用Spring来创建对象,在Spring这些都称为Bean
    类型 变量名 = new 类型();
    Hello hello = new Hello();

    id = 变量名
    class = new的对象
    property 相当于给对象中的属性设置一个值!
        -->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>
复制代码
  1. 测试类MyTest
复制代码
import com.kuang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MyTest {

    public static void main(String[] args) {
        //获取Spring的上下文对象,下方为官方固定写法,参数可多参传入
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象下能在都在spring·中管理了,我们要使用,直接取出来就可以了
        Hello holle = (Hello) context.getBean("hello");
        System.out.println(holle.toString());
    }

}
复制代码

思考问题?

Hello对象是谁创建的?
Hello对象是由Spring创建的。
Hello对象的属性是怎么设置的?
Hello对象的属性是由Spring容器设置的。
这个过程就叫控制反转:

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。

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

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

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

可以通过new ClassPathXmlApplicationContext去浏览一下底层源码。

OK,到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话搞定:对象由Spring来创建,管理,装配!

**弹幕大佬的简易理解:**就相当于你请人吃饭

原来的程序是:你写好菜单买好菜,客人来了自己把菜炒好招待

现在这套程序是:你告诉楼下餐厅,你要哪些菜,客人来的时候,餐厅把做好的你需要的菜送上来

IoC:炒菜这件事,不再由你自己来做,而是委托给了第三方–>餐厅来做

此时的区别就是,如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来

在前面第一个module试试引入Spring:Spring01-ioc模块中

复制代码
<?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">

    <!--
    该id属性是标识单个 bean 定义的字符串。
    该class属性定义 bean 的类型并使用完全限定的类名。
    该id属性的值是指协作对象。
    -->

    <!--使用Spring来创建对象,在Spring这些都成为Bean-->
    <bean id="mysqlImpl" class="com.tongda.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.tongda.dao.UserDaoOracleImpl"/>

    <!--接口实现Impl都要注册,service属性注入-->
    <bean id="serviceImpl" class="com.tongda.service.UserServiceImpl">
        <!--
        ref:引用Spring容器中创建好的对象
        value:具体的值,基本数据类型!
        -->
        <property name="userDao" ref="mysqlImpl"/>
    </bean>
</beans>
复制代码

 第一个module改良后测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
        userServiceImpl.getUser();
    }
}

总结:

所有的类都要装配的beans.xml (spring的配置文件)里面;

所有的bean 都要通过容器去取;

容器里面取得的bean,拿出来就是一个对象,用对象调用方法即可;

4、IOC创建对象的方式

  使用无参构造创建对象,默认。

  使用有参构造(如下)

​     1.下标赋值

​     index指的是User实体类中有参构造中参数的下标,下标从0开始;

    <!--第一种方式:下标赋值    -->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="狂神说Java"/>
    </bean>

​     2. 类型赋值(不建议使用

    <!--第二种方式:通过类型的创建,不建议使用    -->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg type="java.lang.String" value="qinjiang"/>
    </bean>

​     3. 直接通过参数名(掌握

    <!--第三种方式:直接通过参数名来设置    -->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="kuangshen"/>
    </bean>

name方式还需要无参构造和set方法,index和type只需要有参构造

就算是new 两个对象,也是只有一个实例(单例模式:全局唯一

注册bean之后就对象的初始化了(类似 new 类名()) 

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        User user = (User) context.getBean("user");
        User user2 = (User) context.getBean("user");
        System.out.println(user==user2);//true
    }

 总结:在配置文件加载的时候,容器中管理的对象都就已经初始化了!

5、Spring配置

5.1、别名

<bean id="user" class="com.kuang.pojo.User">
    <constructor-arg name="name" value="chen"></constructor-arg>
</bean>

<alias name="user" alias="user2"/>
<!-- 使用时
    User user2 = (User) context.getBean("user2");    
-->

5.2、Bean的配置

复制代码
<!--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");    
-->
复制代码

5.3、import

import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个

假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利
用import将所有人的beans.xml合并为一个总的applicationContext.xml

  张三(beans.xm1)
  李四(beans2.xm1)
  王五(beans3.xm1)
  applicationContext.xml合并beans\beans2\beans3

复制代码
<?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"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>

</beans>
复制代码

 

 使用的时候,直接使用总的配置就可以了

弹幕评论:

按照在总的xml中的导入顺序来进行创建,后导入的会重写先导入的,最终实例化的对象会是后导入xml中的那个

6、依赖注入(DI)

6.1、构造器注入

前面已经介绍过,参考4、IOC创建对象的方式

6.2、set方式注入【重点

依赖注入:set注入!

  依赖:bean对象的创建依赖于容器

  注入:bean对象中的所有属性,由容器来注入

【环境搭建】

  复杂类型

  bean | ref | idref | list | set | map | props | value | null

  Address类 

复制代码
package com.kuang.pojo;

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类

复制代码
public class Student {

    // bean | ref | idref | list | set | map | props | value | null

    //基本类型
    private String name;
    //引用类型
    private Address address;
    //数组类型
    private String[] books;
    //列表
    private List<String> hobbys;
    //map集合 :学生卡
    private Map<String, String> card;
    //set集合:游戏
    private Set<String> games;
    private String wife;
    private Properties info;

    //get and set,toString自己添加
}
复制代码

  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.tongda.pojo.Student">
        <!--第一种:普通值注入,value-->
        <property name="name" value="爵岚"/>
    </bean>

</beans>
复制代码

  测试

  MyTest

复制代码
public class MyTest {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());

    }
复制代码

   完善注入信息

复制代码
<?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.tongda.pojo.Address">
        <property name="address" value="郑州"/>
    </bean>


    <bean id="student" class="com.tongda.pojo.Student">
        <!--第一种:普通值注入,value-->
        <property name="name" value="爵岚"/>

        <!--第二种:bean注入,引用类型,使用ref-->
        <property name="address" ref="address"/>

        <!--数组注入:数组类型,-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国演义</value>
                <value>西游记</value>
                <value>水浒传</value>
            </array>
        </property>

        <!--list注入-->
        <property name="hobbys">
            <list>
                <value>敲代码</value>
                <value>看电影</value>
                <value>睡觉觉</value>
            </list>
        </property>

        <!--Map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="41020211111122115"/>
                <entry key="银行卡" value="621744234456174"/>
            </map>
        </property>
        
        <!--Set集合注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>英雄联盟</value>
                <value>王者荣耀</value>
            </set>
        </property>

        <!--null注入-->
        <!--<property name="wife" value=""/>-->
        <property name="wife">
            <null/>
        </property>
        
        <!--Properties特殊类型注入:<prop key="">值</prop>-->
        <property name="info">
            <props>
                <prop key="dirver"></prop>
                <prop key="url"></prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>

                <prop key="学号">0001</prop>
                <prop key="性别"></prop>
                <prop key="班级">三二班</prop>
            </props>
        </property>

    </bean>

</beans>
复制代码

   MyTest

复制代码
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
    /*
    完善注入结果:
   Student{name='爵岚',
    address=Address{address='郑州'},
    books=[红楼梦, 三国演义, 西游记, 水浒传],
    hobbys=[敲代码, 看电影, 睡觉觉],
    card={
    身份证=41020211111122115,
    银行卡=621744234456174
    },
    games=[LOL, 英雄联盟,王者荣耀],
    wife='null',
    info={
        学号=0001,        性别=男,        班级=三二班,
        password=123456,  dirver=, url=, username=root}}
    */
}
复制代码

6.3、拓展注入

我们可以使用p命名空间和c命名空间进行注入
官方解释:

官方文档位置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o2oigvf3-1635138919645)(C:\Users\吃妹子不吐胖次吖\AppData\Roaming\Typora\typora-user-images\1634818522589.png)]

pojo增加User类

 

复制代码
package com.kuang.pojo;

public class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
复制代码

注意: beans 里面加上这下面两行

使用p和c命名空间需要导入xml约束

xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”

复制代码
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.kuang.pojo.User" p:name="秦疆" p:age="20"/>

    <!--c命名空间注入,通过构造器注入(需要写入有参和无参构造方法):constructor-args-->
    <bean id="user2" class="com.kuang.pojo.User" c:name="狂神" c:age="22" />
</beans>
复制代码

 P命名空间对应的Set注入;

C命名空间对应的构造器注入。

测试

复制代码
@Test
    public void test2(){
        //读取userbeans.xml
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        // User user = (User) context.getBean("user");优化
        //利用反射机制User.class无需强转
        User user = context.getBean("user", User.class);
        System.out.println(user);

        User user2 = context.getBean("user2",User.class);
        System.out.println(user2);    
    
    }             
复制代码

注意点:p命名和c命名空间不能直接使用,需要导入beans.xml约束!

xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”

6.4、Bean作用域:Scopes 单词记忆

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ppehf63z-1635138919645)(C:\Users\吃妹子不吐胖次吖\AppData\Roaming\Typora\typora-user-images\1634819617667.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-60PScxOv-1635138919646)(C:\Users\吃妹子不吐胖次吖\AppData\Roaming\Typora\typora-user-images\1634819854644.png)]

    1. 单例模式(Spring默认机制):scope="singleton"单例模式:user==user2 结果:true
<!--scope="singleton"单例模式:user==user2 结果:true-->
<bean id="user" class="com.kuang.pojo.User" p:name="秦疆" p:age="20" scope="singleton"/>
复制代码
    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        User user = context.getBean("user",User.class);
        System.out.println(user.hashCode());//797925218

        User user2 = context.getBean("user",User.class);
        System.out.println(user2.hashCode());//797925218

        System.out.println(user==user2);//true
    }
复制代码
  1. 原型模式:每次从容器中get的时候,都会产生一个新对象!:user==user2 结果:false

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Scp2Uj5H-1635138919647)(C:\Users\吃妹子不吐胖次吖\AppData\Roaming\Typora\typora-user-images\1634820506179.png)]

<bean id="user2" class="com.kuang.pojo.User" c:name="狂神" c:age="22" scope="prototype" />
复制代码
    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        User user = context.getBean("user2",User.class);
        System.out.println(user.hashCode());//1615039080

        User user2 = context.getBean("user2",User.class);
        System.out.println(user2.hashCode());//336484883

        System.out.println(user==user2);//false
    }
复制代码
  1. 其余的request、session、application这些只能在web开放中使用!

7、Bean的自动装配

  自动装配是Spring满足bean依赖的一种方式
  Spring会在上下文自动寻找,并自动给bean装配属性

在Spring中有三种装配的方式

  1、在xml中显示配置

  2、在java中显示配置

  3、隐式的自动装配bean 【重要

  4、byName自动装配:byName会自动查找,和自己对象set对应的值对应的id

保证所有id唯一,并且和set注入的值一致

7.1 测试

环境搭建:创建项目,一个人有两个宠物!

  1. Dog
package com.kuang.pojo;

public class Dog {
    public void shout(){
        System.out.println("wang~");
    }
} 
  1. Cat
package com.kuang.pojo;

public class Cat {
    public void shout(){
        System.out.println("miao~");
    }
}

  3.Person

复制代码
public class Person {

    private String name;
    //引用类型:拥有猫和狗
    private Cat cat;
    private Dog dog;

    public Person() {
    }

    public Person(String name, Cat cat, Dog dog) {
        this.name = name;
        this.cat = cat;
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = 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;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", cat=" + cat +
                ", dog=" + dog +
                '}';
    }
}
复制代码
  1. 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 http://www.springframework.org/schema/beans/spring-beans.xsd">

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

    <bean id="person" class="com.kuang.pojo.Person">
        <property name="name" value="kuangshen"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>

</beans>
复制代码
  1. MyTest
复制代码
    @Test
    public void Test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        Person person = context.getBean("person", Person.class);

        person.getCat().shout();
        person.getDog().shout();
    }
复制代码

7.2 ByName自动装配

byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id!
保证所有id唯一,并且和set注入的值一致

复制代码
   <bean id="cat" class="com.tongda.pojo.Cat"/>
    <bean id="dog" class="com.tongda.pojo.Dog"/>
    
    <!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id!
                保证所有id唯一,并且和set注入的值一致
                例如:setDog(),取set后面的字符作为id,则要id = dog 才可以进行自动装配
    -->
    <!--使用自动装配时,autowire="byName"-->
    <bean id="person" class="com.tongda.pojo.Person" autowire="byName">
        <property name="name" value="爵岚"/>
        
        <!--<property name="cat" ref="cat"/>-->
        <!--<property name="dog" ref="dog"/>-->

    </bean>
复制代码

7.3 ByType自动装配

复制代码
   <bean class="com.tongda.pojo.Cat"/>

  <bean class="com.kuang.pojo.Dog"/>
  <!--byType:byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
                保证所有的class唯一(类为全局唯一),即使没有id也可以成功
                例如,Dog dog; 那么就会查找pojo的Dog类,再进行自动装配
    -->
    <bean id="person" class="com.kuang.pojo.Person" autowire="byType">
        <property name="name" value="kuangshen"/>
    </bean>
复制代码

 

小结:

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

 

7.4 使用注解实现自动装配

jdk1.5支持的注解,Spring2.5就支持注解了!

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用注解须知:

  1、导入约束.context

  2、配置注解的支持[重要!] :<!--开启注解支持--> <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/>

    <bean id="cat" class="com.tongda.pojo.Cat"/>
    <bean id="dog" class="com.tongda.pojo.Dog"/>
    <bean id="people" class="com.tongda.pojo.People"/>

</beans>
复制代码

@Autowired

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

使用Autowired我们就可以不用编写set方法了,前提是你这个自动配置的属性在IOC(Spring)容器中存在,且符合名字ByName!

科普:

@Nullable 字段标记了了这个注解,说明这个字段可以为null;
public @interface Autowired {
    boolean required() default true;
}

如果定义了Autowire的require属性为false,说明这个对象可以为null,否则不允许为空(false表示找不到装配,不抛出异常)

测试代码:

public class Person {
    //如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

 @Autowired+@Qualifier

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

复制代码
public class Person {
    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}
复制代码

弹幕评论:如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找

@Resource

public class Person {

    @Resource
    private Cat cat;

    @Resource(name="dog111")
    private Dog dog;
}

小结:

@Resource和@Autowired的区别

都是用来自动装配的,都可以放在属性字段上

@Autowired通过byType的方式实现,当匹配到多个同类型时,使用ByName进行装配, 而且必须要求这个对象存在!【常用】

@Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】

执行顺序不同:@Autowired通过byType的方式实现。@Resource默认通过byName的方式实现。

 

8、使用注解开发 AOP

确保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: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/>
    <!--扫描机制:指定扫描包下的注解-->
    <context:component-scan base-package="com.tongda.pojo"/>

</beans>
复制代码

  1、bean

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

<context:component-scan /> 除了具有context:annotation-config的功能之外,<context:component-scan />还可以在指定的package下扫描以及注册javabean 。还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能。因此当使用 <context:component-scan />后,就可以将 <context:annotation-config />移除。

  2、属性如何注入@Value

复制代码
//等价于 <bean id= "user" class= "com.kuang.pojo.User"/>
//@Component 组件

@Component
public class User {

    //相当于<property name= "name”value= "kuangshen"/>
    @Value("kuangshen")
    public String name;
    
    //也可以放在set方法上面
    //@value("kuangshen")
    public void setName(String name) { 
        this.name = name; 
    }
}
复制代码

   3、衍生的注解

@Component有几个衍生注解,会按照web开发中,mvc架构中分层。

  dao (@Repository)
  service(@Service)
  controller(@Controller)
这四个注解功能都是一样的,都是代表将某个类注册到Spring容器中,装配Bean

  4、自动装配

@Autowired:默认是byType方式,如果匹配不上,就会byName.如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = “xxx”)去配置。先类型后名字

@Nullable:字段标记了这个注解,说明该字段可以为空.

@Resource:默认是byName方式,如果匹配不上,就会byType.先名字后类型

  5、作用域@Scope

复制代码
//等价于 <bean id= "user" class= "com.kuang.pojo.User"/>
//@Component 组件

@Component
//scope("prototype")相当于<bean scope="prototype">原型模式</bean>或者scop="singleton"单例模式
@Scope("prototype")
public class User {

    //相当于<property name= "name”value= "kuangshen"/>
    @Value("kuangshen")
    public String name;
}
复制代码

   6、小结 

xml与注解:

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

最佳实践:

  • xml用来管理bean
  • 注解只用来完成属性的注入
  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.kuang"/>
    <!--开启注解支持-->
    <context:annotation-config/>

9、使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6hTh0ICb-1635138919648)(C:\Users\吃妹子不吐胖次吖\AppData\Roaming\Typora\typora-user-images\1634957290384.png)]

实体类User

复制代码
//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("QINIIANG")//属性注入值
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
复制代码

 配置文件AppConfig

复制代码
// 这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component
// @Configuration表这是一个配置类,就像我们之前看的beans.xml一样,类似于<beans>标签
@Configuration
@ComponentScan("com.kuang.pojo") //开启扫描
@Import(KuangConfig.class)//Import将所有的@Configuration合并为一个总的!
public class AppConfig {

    //注册一个bean , 就相当于我们之前写的一个bean 标签
    //这个方法的名字,就相当于bean 标签中的 id 属性 ->getUser
    //这个方法的返同值,就相当于bean 标签中的class 属性 ->User
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的对象!
    }
}
复制代码
@Configuration
public class KuangConfig {
}

测试类MyTest

复制代码
public class MyTest {
    @Test
    public void Test01(){
        //如果完全使用了配置类方式去做,我们就只能通过 Annotationconfig 上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);//class对象

        User user = (User) context.getBean("getUser");//方法名getUser

        System.out.println(user.getName());
    }
}
复制代码

这种纯Java的配置方式,在SpringBoot中随处可见!

 

10、代理模式

为什么要学习代理模式?因为这就是SpringAOP的底层!【SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

 

10.1 静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理对象的人!

代码步骤:

  1. 接口
//租房
public interface Rent {
    public void rent();
}
  1. 真实角色
//房东
public class Host implements Rent{
    public void rent() {
        System.out.println("房东出租房子!");
    }
}
  1. 代理角色
复制代码
public class Proxy implements Rent{
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        host.rent();
        seeHouse();
        sign();
        fee();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带着看房子!");
    }

    //签合同
    public void sign(){
        System.out.println("和中介签署租赁合同!");
    }

    //收费用
    public void fee(){
        System.out.println("中介收取费用!");
    }
}
复制代码
  1. 客户端访问代理角色 
复制代码
public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
        //host.rent();

        //代理,中介帮房东出租房子,并且代理角色一般会有一些附属操作!
        Proxy proxy = new Proxy(host);

        //不用面对房东,直接找中介租房即可!
        proxy.rent();
    }
}
复制代码

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共业务就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率会变低~

10.2 加深理解

代码步骤:

  1. 接口

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

  2. 真实角色

复制代码
//真实角色
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("查询了一个用户!");
    }
}
复制代码

  3. 代理角色

复制代码
public class UserServiceProxy implements UserService{
    private 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.query();
    }

    public void log(String msg){
        System.out.println("[Debug] 使用了一个"+msg+"方法");
    }
}
复制代码

  4. 客户端访问代理角色 

复制代码
public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();

        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);

        proxy.delete();
    }
}
复制代码

聊聊AOP

 

10.3 动态代理 

  动态代理和静态代理角色一样
  动态代理的代理类是动态生成的,不是我们直接写好的!
  动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    基于接口 — JDK动态代理【我们在这里使用】
    基于类:cglib
    java字节码实现:javassist
需要了解两个类:Proxy:代理;InvocationHandler:调用处理程序

代码步骤: 

  1. 接口 
//公共类:租房
public
interface Rent { public void rent(); }

   2. 真实角色

//房东
public
class Host implements Rent{ public void rent() { System.out.println("房东要出租房子!"); } }
  1. ProxyInvocationHandler类 
复制代码
//等我们会用这个类,自动生成代理类!
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);
//自动生成得到代理类:固定代码,参数只有rent接口名变动
    public Object getProxy(){
        //参数:this.getClass().getClassLoader():加载类在哪个位置
        //参数:rent.getClass().getInterfaces():代表代理接口是哪个
        //参数:this:代表InvocationHandler
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //动态代理的本质,就是使用反射机制invoke实现
        Object result = method.invoke(rent, args);
        seeHose();
        fee();
        return result;
    }

    public void seeHose(){
        System.out.println("中介带着看房子!");
    }

    public void fee(){
        System.out.println("中介收取费用!");
    }
}
复制代码
  1. 客户调用测试
复制代码
public class Client {
    @Test
    public void test(){
        //真实角色:房东
        Host host = new Host();

        //代理角色:暂时没有
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        //通过调用程序处理角色来处理我们要调用的接口对象!
        pih.setRent(host);//传入需要代理的接口

        //调用getProxy()方法:生成的代理类
        //这里的proxy就是动态生成的,我们并没有写
        Rent proxy = (Rent) pih.getProxy();

        //使用代理对象调用方法
        proxy.rent();
    }
}
复制代码

避免写死在此,我们可以提炼出ProxyInvocationHandler作为工具类

复制代码
//我们会用这个类,自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {

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

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

    //自动生成得到代理类
//    Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
//            new Class<?>[] { Foo.class },
//            handler);
    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+"方法");
    }
}
复制代码

避免写死详细演变

复制代码
//等我们会用这个类,自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口:避免写死
    // private Rent rent;

    // public void setRent(Rent rent) {
    //     this.rent = rent;
    // }
    private Object target;

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

    //    Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
//            new Class<?>[] { Foo.class },
//            handler);
    //自动生成得到代理类:固定代码,参数只有rent接口名变动
    public Object getProxy(){
        //参数:this.getClass().getClassLoader():加载类在哪个位置
        //参数:rent.getClass().getInterfaces():代表代理接口是哪个
        //参数:this:代表InvocationHandler
        // return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }


    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //动态代理的本质,就是使用反射机制invoke实现
        // seeHose();
        // Object result = method.invoke(rent, args);
        Object result = method.invoke(target, args);
        // fee();
        return result;
    }

    // public void seeHose(){
    //     System.out.println("中介带着看房子!");
    // }
    //
    // public void fee(){
    //     System.out.println("中介收取费用!");
    // }
}
复制代码

动态万能写法:都是官方固定写法,只有参数rent变更

复制代码
//等我们会用这个类,自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口:避免写死
    // private Rent rent;

    // public void setRent(Rent rent) {
    //     this.rent = rent;
    // }
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }
 //自动生成得到代理类:固定代码,参数只有rent接口名变动
    public Object getProxy(){
        //参数:this.getClass().getClassLoader():加载类在哪个位置
        //参数:rent.getClass().getInterfaces():代表代理接口是哪个
        //参数:this:代表InvocationHandler
        // return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质,就是使用反射机制invoke实现
        //原方法: logs("add");
        //使用反射机制,避免写死
        logs(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    //增加功能log
    public void logs(String msg){
        System.out.println("执行了"+msg+"方法");
    }
}
复制代码

Demo02用户测试

复制代码
public class Client2 {
    public static void main(String[] args) {
        //真实对象
        UserServiceImpl userService = new UserServiceImpl();

        //new一个动态代理类,使其自动生成相应的代理对象
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        //传入需要代理的接口
        pih.setTarget(userService);
        UserService proxy = (UserService) pih.getProxy();//调用方法,自动生成代理对象

        //使用代理对象,完成业务
        proxy.add();
    }
}
复制代码
复制代码
化demo02代理
public class Client {
    @Test
    public void test(){
        //真实角色:dome02中
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色,不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        //设置要代理的对象
        pih.setTarget(userService);
        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();

        proxy.add();
        proxy.query();
        proxy.delete();
        proxy.update();
    }
}
复制代码

 动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共角色就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可!

11、AOP

 11.1 什么是AOP

弹幕解释理解:其实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:pointcut  切入点

  aop:aspect  切入面

  aop:advice  通知 关联

 

 重点】使用AOP织入,需要导入一个依赖包! 

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.9.1</version>
    <scope>runtime</scope>
</dependency>

 

方式一: 使用Spring的API接口【主要是SpringAPI接口实现

  1. 在service包下,定义UserService业务接口
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}

UserServiceImpl实现类

复制代码
public class UserServiceImpl implements UserService{

    @Override
    public void add() {
        System.out.println("增加用户");
    }

    @Override
    public void delete() {
        System.out.println("删除用户");
    }

    @Override
    public void update() {
        System.out.println("修改用户");
    }

    @Override
    public void select() {
        System.out.println("查询用户");
    }
}
复制代码
  1. 在log包下,定义我们的增强类,一个Log前置增强和一个AfterLog后置增强类
复制代码
// 使用spring方式:aop.MethodBeforeAdvice
public class Log implements MethodBeforeAdvice {

    @Override
    /*
    method:要执行的目标对象的方法
    args:参数
    target:目标对象
    */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被执行了");
    }
}
复制代码
//使用spring中aop.AfterReturningAdvice
public class AfterLog implements AfterReturningAdvice {
    @Override
    //returnValue: 返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}
  1. 最后去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束,配置applicationContext.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: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.tongda.service.UserServiceImpl"/>
    <bean id="log" class="com.tongda.log.Log"/>
    <bean id="afterLog" class="com.tongda.log.AfterLog"/>

    <!--方式一:使用原生Spring API接口
    配置aop:需要导入aop的约束
    配置aop:config内容,把切入点和通知结合-->

    <!--proxy-target-class:使用cglib实现代理
    expression 表达式:*任意
    execution(*         com.gyf.service.*.   *    (..))
             返回值       包名           类名 方法名  参数-->
  
    <aop:config>
        <!--aop:advisor切入点:expression:表达式,execution(要执行的位置!* * * * *)-->
        <!--execution(*返回值 包名.类名.*方法(..参数) -->
        <aop:pointcut id="pointcut" expression="execution(* com.tongda.service.UserServiceImpl.*(..))"/>

        <!-- 通知 关联 切入点-->
        <!--执行环绕增加!-->
        <!--将log\afterLog 关联advice 切入点pointcut-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>

</beans>
复制代码

切入点表达式:

整个表达式可以分为五个部分:

1、execution(): 表达式主体。

2、第一个*号:方法返回类型, *号表示所有的类型。

3、包名:表示需要拦截的包名。

4、第二个*号:表示类名,*号表示所有的类。

5、*(…):最后这个星号表示方法名,*号表示所有的方法,后面( )里面表示方法的参数,两个句点表示任何参数

  1. 测试
复制代码
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //注意点:动态代理代理的是接口UserService,不是UserServiceImpl接口实现类
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();
        userService.select();
        userService.delete();
    }
}
复制代码

方式二: 自定义类来实现AOP【主要是切面定义

  1. 在diy包下定义自己的DiyPointCut切入类
复制代码
public class DiyPointCut {
    public void before(){
        System.out.println("======方法执行前======");
    }

    public void after(){
        System.out.println("======方法执行后======");
    }
} 
复制代码
  1. 去spring中配置文件
复制代码
    <!--方式二:自定义类-->
    <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.*(..))"/>
            <!--通知 方法method 切入点-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
复制代码
  1. 测试 
复制代码
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //注意点:动态代理代理的是接口UserService,不是UserServiceImpl接口实现类
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();
        userService.select();
        userService.delete();
        userService.update();
    }
}
复制代码

方式三: 使用注解实现!

  1. 在diy包下定义注解实现的AnnotationPointCut增强类
复制代码
//声明式事务!
@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);
    }
}
复制代码
  1. 在Spring配置文件中,注册bean,并增加支持注解的配置。
    <!--方式三:使用注解-->
    <bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
    <!--开启注解支持! JDK(默认是 proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy/>
  1. 测试结果
环绕前
signature:void com.kuang.service.UserService.add()
====方法执行前====
增加了一个用户!
====方法执行后====
环绕后
null

12、整合Mybatis(2020-11-21)

mybatis-spring官网:https://mybatis.org/spring/zh/

步骤:

 1、导入相关jar包
  1、junit
  2、mybatis
  3、mysql数据库
  4、spring相关
  5、aop织入器
  6、mybatis-spring整合包【重点】在此还导入了lombok包。
  7、配置Maven静态资源过滤问题!

复制代码
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.19</version>
        </dependency>
        <!--Spring操作数据库的话,还需要一个spring-jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.19</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

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

</project>
复制代码
  1. 编写配置文件

  2. 测试

 

12.1 回忆mybatis

  1. 编写pojo实体类
@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

   2. 编写实现mybatis的配置文件mybatis-config.xml

复制代码
<?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核心配置文件-->
<configuration>
    <!--注意点:核心配置文件书写标签配置顺序,properties放在最前面-->
    <!--引入外部配置文件,资源resource=“路径”-->
    <properties resource="db.properties"/>

    <!--日志配置-->
    <settings>
        <!--标准的日志工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--<setting name="logImpl" value="LOG4J"/>-->
    </settings>

    <!--注意标签书写顺序-->
    <!--可以给实体类别名-->
    <typeAliases>
        <!--指定一个类,起别名-->
        <!--<typeAlias type="com.tongda.pojo.User" alias="User"/>-->
        <!--指定一个包,包别名均为小写类名-->
        <package name="com.tongda.pojo"/>
    </typeAliases>

    <!--environments多环境配置 default默认=id-->
    <environments default="development">
        <!--environment环境 id-->
        <environment id="development">
            <!--事务管理 JDBC-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">

                <!--引入外部配置文件后,不用写死value值-->
                <!--<property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->
                <property name="driver" value="${driver}"/>
                <!--<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>-->
                <property name="url" value="${url}"/>
                <!--<property name="username" value="root"/>-->
                <property name="username" value="${username}"/>
                <!--<property name="password" value="123456"/>-->
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--<mapper resource="com/tongda/dao/*Mapper.xml"/>-->
        <mapper class="com.tongda.mapper.UserMapper"/>

        <!--<package name="com.tongda.dao"/>-->
    </mappers>

</configuration>
复制代码
  1. 编写UserMapper接口
public interface UserMapper {
    public List<User> selectUser();
}
  1. 编写UserMapper.xml文件
复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.kuang.mapper.UserMapper">

    <!--sql-->
    <select id="selectUser" resultType="user">
        select * from mybatis.user
    </select>
</mapper>
复制代码
  1. 测试
复制代码
public class MyTest {
    @Test
    public void test() throws IOException {
        //没有utils工具类情况下
        // 1.加载资源路径
        String resources = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);

        // SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
        //优化
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //自动提交sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //反射
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
sqlSession.close(); } }
复制代码

12.2 Mybatis-Spring

什么是MyBatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。

文档链接:http://mybatis.org/spring/zh/index.html

如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可: 

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>

整合实现一:【必须掌握】

  1. 引入Spring配置文件spring-dao.xml
<?xml version="1.0" encoding="GBK"?>
<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

</beans>
  1. xml中配置数据源替换mybaits的数据源
    <!--DataSource数据源:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
  1. xml中配置SqlSessionFactory,关联MyBatis[核心]
复制代码
<!--固定代码-->
    <!--SqlSessionFactory官网:入门写法-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--扩展:关联mybatis配置文件-->
        <!--configuration核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--映射配置-->
        <property name="mapperLocations" value="classpath:com/tongda/mapper/*.xml"/>
    </bean>
复制代码
  1. 注册sqlSessionTemplate,关联sqlSessionFactory【核心】
<!--固定代码-->
    <!--Template模板:XXXXTemplate\SqlTemplate\redisTemplate-->
    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
  1. 需要UserMapper接口的UserMapperImpl 实现类,私有化sqlSessionTemplate,对应官方bean就可以直接注入到你的DAO bean中了,你需要在你的bean中添加一个SqlSession属性。
复制代码
public class UserMapperImpl implements UserMapper{

    //我们的所有操作,都使用sqlSession来执行在原来,现在都使用SqlsessionTemplate
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return  mapper.selectUser();
    }
}
复制代码
  1. 将自己写的实现类,注入到Spring配置文件中。
    <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
  1. 测试使用即可!
复制代码
public class MyTest {
    @Test
    public void test() throws IOException {
        //没有工具类情况下
        // 1.加载资源路径
        String resources = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);

        // SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
        //优化
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //自动提交sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

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

        sqlSession.close();
    }

    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);

        }
    }
}
复制代码

结果成功输出!现在我们的Mybatis配置文件的状态!发现都可以被Spring整合!

整合实现二:

mybatis-spring1.2.3版以上的才有这个,官方文档截图:

dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起整合方式一 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看。

 测试:

  1. 将我们上面写的UserMapperImpl修改一下为UserMapperImpl2
复制代码
// spring整合二:继承SqlSessionDaoSupport
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    
    @Override
    public List<User> selectUser() {
        /*SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();*/
        //优化:官方推荐
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}
复制代码
  1. 注入到Spring配置文件中
</bean>
    <!--注册UserMapperImpl2-->
    <bean id="userMapper2" class="com.tongda.mapper.UserMapperImpl2">
        <!--没有属性注入,所以父类需要注入sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

  3. 测试

复制代码
    @Test
    public void test () throws IOException {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
复制代码

总结:

整合一:必须掌握

整合二:只是简化

mybatis-plus和通用mapper熟悉

 

配置文件经过整合后分别为:

mybatis-config.xml:

复制代码
<?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核心配置文件-->
<configuration>

    <!--日志配置-->
    <settings>
        <!--标准的日志工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--<setting name="logImpl" value="LOG4J"/>-->
    </settings>

    <!--注意标签书写顺序-->
    <!--可以给实体类别名-->
    <typeAliases>
        <!--指定一个类,起别名-->
        <!--<typeAlias type="com.tongda.pojo.User" alias="User"/>-->
        <!--指定一个包,包别名均为小写类名-->
        <package name="com.tongda.pojo"/>
    </typeAliases>

</configuration>
复制代码

spring-dao.xml:专注于做dao层

复制代码
<?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">

    <!--DataSource数据源:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--固定代码-->
    <!--SqlSessionFactory官网:入门写法-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--扩展:关联mybatis配置文件-->
        <!--configuration核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--映射配置-->
        <property name="mapperLocations" value="classpath:com/tongda/mapper/*.xml"/>
    </bean>

    <!--固定代码-->
    <!--Template模板:XXXXTemplate\SqlTemplate\redisTemplate-->
    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--合并配置:移动到applicationContext.xml中-->
    <!--<bean id="userMapper" class="com.tongda.mapper.UserMapperImpl">-->
    <!--    <property name="sqlSession" ref="sqlSessionTemplate"/>-->
    <!--</bean>-->

</beans>
复制代码

applicationContext.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: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">

    <!--合并配置:导入xml-->
    <import resource="spring-dao.xml"/>
    <!--<import resource="spring-mvc.xml"/>-->

    <!--注册UserMapperImpl-->
    <bean id="userMapper" class="com.tongda.mapper.UserMapperImpl">
        <!--注入属性-->
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
    <!--注册UserMapperImpl2-->
    <bean id="userMapper2" class="com.tongda.mapper.UserMapperImpl2">
        <!--没有属性注入,所以父类注入sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>
复制代码

13、声明式事务

13.1 回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败!
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎!
  • 确保完整性和一致性。

事务ACID原则:

  原子性(atomicity)

  事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用。
  一致性(consistency)

  一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中。
  隔离性(isolation)

  可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏。
  持久性(durability)

  事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中。

 

测试:

将上面章节12的代码拷贝到一个新项目中
在之前的案例中,我们给userMapper接口新增两个方法,删除和增加用户;

1、User实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

2、mybatis-config.xml

复制代码
<?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核心配置文件-->
<configuration>

    <!--日志配置-->
    <settings>
        <!--标准的日志工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--<setting name="logImpl" value="LOG4J"/>-->
    </settings>

    <!--注意标签书写顺序-->
    <!--可以给实体类别名-->
    <typeAliases>
        <!--指定一个类,起别名-->
        <!--<typeAlias type="com.tongda.pojo.User" alias="User"/>-->
        <!--指定一个包,包别名均为小写类名-->
        <package name="com.tongda.pojo"/>
    </typeAliases>

</configuration>
复制代码

3、spring-dao.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: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">

    <!--DataSource数据源:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--固定代码-->
    <!--SqlSessionFactory官网:入门写法-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--扩展:关联mybatis配置文件-->
        <!--configuration核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--映射配置-->
        <property name="mapperLocations" value="classpath:com/tongda/mapper/*.xml"/>
    </bean>

    <!--固定代码-->
    <!--Template模板:XXXXTemplate\SqlTemplate\redisTemplate-->
    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--合并配置:移动到applicationContext.xml中-->
    <!--<bean id="userMapper" class="com.tongda.mapper.UserMapperImpl">-->
    <!--    <property name="sqlSession" ref="sqlSessionTemplate"/>-->
    <!--</bean>-->

</beans>
复制代码

4、UserMapper接口,给userMapper接口新增两个方法,删除和增加用户;

复制代码
public interface UserMapper {
    public List<User> selectUser();

    //添加一个用户
    public int addUser(User user);

    //删除一个用户
    public int deleteUser(int id);
    // 在方法参数的前面写上@Param("参数名"),表示给参数命名,名称就是括号中的内容
    // public int deleteUser(@Param("id") int id,@Param("name") String name);

}
复制代码

5、UserMapper.xml文件,我们故意把 deletes写错,测试!

复制代码
<?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.tongda.mapper.UserMapper">
    <!--id对应UserMapper接口selectUser()方法名,resultTyper对应mybatis-config.xml别名<typeAliases>中-->
    <select id="selectUser" resultType="user">
        select * from mybatis.user
    </select>

    <!--添加一个用户-->
    <!--id="方法名“ parameterType="参数”-->
    <insert id="addUser" parameterType="user">
        /*  #{}预编译比较安全  */
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
    </insert>

    <!--删除一个用户-->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id};
        /*    故意错误
        deletes from mybatis.user where id=#{id};*/
    </delete>
</mapper>
复制代码

6、UserMapperImlpl实现类

整合方式一:[必会] 

复制代码
public class UserMapperImpl implements UserMapper{

    //我们的所有操作,都使用SqlSession来执行在原来,现在都是用SqlSessionTemplate;
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }

    @Override
    public int addUser(User user) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.deleteUser(id);
    }
}
复制代码

 整合方式二:继承SqlSessionDaoSupport 使用 getSqlSession()

复制代码
// spring整合二:继承SqlSessionDaoSupport
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUser() {
        /*SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();*/
        //优化:官方推荐
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}
复制代码
复制代码
// 整合方法二
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
        // return getSqlSession().getMapper(UserMapper.class).selectUser();

        //UserMapper.xml中delete错误事务
        User user = new User(5, "爵岚", "123123");

        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);

        mapper.addUser(user);
        mapper.deleteUser(5);

        return mapper.selectUser();
    }

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

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}
复制代码
复制代码
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{


    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);

        //在测试中增删对象,查看事务是否一致成功,一致失败
        mapper.addUser(new User(5,"测试对象","888888"));
        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);
    }
}
复制代码

 

7、applicationContext.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: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">

    <!--合并配置:导入xml-->
    <import resource="spring-dao.xml"/>
    <!--<import resource="spring-mvc.xml"/>-->

    <!--注册UserMapperImpl-->
    <bean id="userMapper" class="com.tongda.mapper.UserMapperImpl">
        <!--注入属性-->
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
    <!--注册UserMapperImpl2-->
    <bean id="userMapper2" class="com.tongda.mapper.UserMapperImpl2">
        <!--没有属性注入,所以父类注入sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>
复制代码

8、MyTest

复制代码
public class MyTset {
    @Test
    public void test(){
        //获取配置文件,创建对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}
复制代码

报错:sql异常,deleteSQL语句写错了

结果 :数据库结果显示插入成功!

没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!

以前我们都需要自己手动管理事务,十分麻烦!

但是Spring给我们提供了事务管理,我们只需要配置即可;

13.2 Spring中的事务管理

Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。

编程式事务管理:  需要

  • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
  • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

声明式事务管理:  AOP[掌握]

  • 一般情况下比编程式事务好用。
  • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
  • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

1. 使用Spring管理事务,注意头文件的约束导入 : tx 

复制代码
<?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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">
复制代码

2. JDBC事务 

<!--配置声明式事务:Spring 的配置文件中创建一个 DataSourceTransactionManager 对象-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--无属性创建-->
        <constructor-arg ref="dataSource"/>
        <!--有属性创建-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

3. 配置好事务管理器后我们需要去配置事务的通知 

复制代码
<!--结合AOP实现事务的织入-->
    <!--第一步:配置事务通知(的类)固定写法-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务增加传播特性:new propagation="required"默认-->
        <tx:attributes>
            <!--给所有方法配置事务:真正必写方法事务-->
            <tx:method name="*" propagation="REQUIRED"/>
            <!--以下为扩展-->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <!--查询:配置事务只读特性read-only="true"-->
            <tx:method name="query" read-only="true"/>
        </tx:attributes>
    </tx:advice>
复制代码

spring事务传播特性:(了解即可) 

事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:

  propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。

  propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。

  propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。

  propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。

  propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

  propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。

  propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作。

Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。

就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!

 4. 配置AOP,导入aop的头文件

<!--第二步:配置事务切入-->
    <aop:config>
        <!--切入点:id=“随意起” expression="表达式execution(* 包名.类名*.方法*.(所有参数..))"-->
        <aop:pointcut id="txPointCut" expression="execution(* com.tongda.mapper.*.*(..))"/>
        <!--切面:advisor通知要对应id-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
    <!--配置事务切入-->
    <aop:config>                            <!--mapper包下的所有类,所有方法,任意参数-->
        <aop:pointcut id="txPointCut" expression="execution(* mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

 5. 删掉刚才插入的数据,再次测试!

复制代码
    @Test
    public void Test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        List<User> userList = userMapper.selectUser();

        for (User user : userList) {
            System.out.println(user);
        }
    }
复制代码

思考:

为什么需要事务?

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

 

 

posted @   爵岚  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示