【SSM框架】Spring入门

1.1、简介

  • 2002,首次推送了spring框架的雏形:interface21框架
  • spring框架已interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版。
  • Rod Johnson,spring framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,它是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
  • spring理念:使现在的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
  • SSH:Structs + Spring + Hibernate
  • SSM:SpringMVC + Spring + Mybatis
  • 官网:https://spring.io/
  • github地址:https://github.com/spring-projects/spring-framework
  • 中文文档:Spring Framework 中文文档 - Spring Framework 5.1.3.RELEASE Reference | Docs4dev
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.22</version>
</dependency>

1.2、优点

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

总结一句话:spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!

1.3、组成

img

spring框架是一个分层架构,由7个模块组成,spring模块构建在核心容器之上,核心容器定义了创建、配置和管理bean的方式。

img

组成spring框架的每个模块(或者组件)都可以单独存在,或者与其他一个或者多个模块联合实现。每个模块的功能如下:

  • 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
  • Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
  • Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
  • Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
  • Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
  • Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
  • Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。

1.4、拓展

在spring的官网有这个介绍:现代化的java开发!说白就是基于spring的开发!

image-20220502111643372

  • Spring Boot

    • Spring Boot 是 Spring 的一套快速配置脚手架

    • 可以基于Spring Boot 快速开发单个微服务;

  • Spring Cloud

    • Spring Cloud是基于Spring Boot实现的;

因为现在大多数公司都在使用springboot进行快速开发,学习springboot的前提,需要完全掌握spring和springmvc!承上启下的作用!

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

2、IOC理论推导

新建一个空白的maven项目

我们先用我们原来的方式写一段代码

  1. UserDao

    public interface UserDao {
        void getUser();
    }
    
    
  2. UserDaoMySQLImpl

    public class UserDaoMySQLImpl implements UserDao{
        @Override
        public void getUser() {
            System.out.println("MySQL获取用户数据");
        }
    }
    
    
  3. UserService

    package com.sue.service;
    
    public interface UserService {
        void getUser();
    }
    
    
  4. UserServiceImpl

    public class UserServiceImpl implements UserService{
    
        private UserDao userDao = new UserDaoMySQLImpl();
    
     
    
        @Override
        public void getUser() {
            userDao.getUser();
        }
    }
    
    
  5. 测试一下

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

现在我们修改一下,把Userdao的实现类增加一个

public class UserDaoImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("默认获取用户的数据");
    }
}

我们要使用mysql的话,就需要去service类里修改对应的实现

public class UserServiceImpl implements UserService{

    private UserDao userDao = new UserDaoImpl();

    
    @Override
    public void getUser() {
        userDao.getUser();
    }
}

假设我们的这种需求非常大 , 需要去service实现类里面修改对应的实现。这种方式就根本不适用了, 甚至反人类对吧 , 每次变动 , 都需要修改大量代码 。 这种设计的耦合性太高了,牵一发而动全身。

那我们如何解决?

我们可以在需要用到他的地方 , 不去实现它 , 而是留出一个接口 , 利用set , 我们去代码里修改下

public class UserServiceImpl implements UserService{

    private UserDao userDao;

    //使用set进行动态注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void getUser() {
        userDao.getUser();
    }
}

测试

import com.sue.dao.UserDao;
import com.sue.dao.UserDaoImpl;
import com.sue.service.UserService;
import com.sue.service.UserServiceImpl;

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

        ((UserServiceImpl)userService).setUserDao(new UserDaoImpl());

        userService.getUser();

    }
}

这里发生了革命性的改变

  • 之前,程序是主动创建对象,控制权在程序员手上

  • 使用set注入之后,程序不再具有主动性,而是变成了被动接受的对象!

这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了。系统的耦合性大大降低了,可以更加注重在业务上的实现,这是ioc的原型。

2.1、IOC本质

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

IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

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

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

3、HelloSpring

  1. 导包

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.22</version>
    </dependency>
    
  2. 编写代码

    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 + '\'' +
                    '}';
        }
    }
    
  3. 编写我们的spring文件,这里命名为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就是java对象 , 由Spring创建和管理
            使用spring来创建对象,在spring这些都称为bean
    
            类型 变量名 = new 类();
            Hello helloSpring = new Hello();
    
            id = 变量名
            class = new 的对象
            property相当于给对象中属性设置一个值!
    -->
        <bean id="hello" class="com.sue.pojo.Hello">
            <property name="str" value="Spring"/>
        </bean>
    
    </beans>
    
  4. 测试

    public class MyTest {
        public static void main(String[] args) {
            //获取Spring的上下文对象
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            //我们的对象现在都在Spring中管理,我们要使用直接取出来即可
            Hello hello = (Hello) context.getBean("hello");
            System.out.printf(hello.toString());
        }
    
    }
    
    

思考:

  • Hello 对象是谁创建的 ?

    hello 对象是由Spring创建的

  • Hello 对象的属性是怎么设置的 ?

    hello 对象的属性是由Spring容器设置的

这个过程就叫控制反转:

  • 控制:谁在控制对象的创建,传统的应用程序的对象是由程序本身控制创建的,使用spring后,对象由spring来创建
  • 反转:程序本身不创建对象,而变成被动的接收对象

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

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

修改一下一开始的案例

新增一个spring配置文件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="mysqlImpl" class="com.sue.dao.UserDaoMySQLImpl"></bean>

    <bean id="userdaoImpl" class="com.sue.dao.UserDaoImpl"></bean>

<!--  ref:引用spring容器中创建好的对象
      value:具体的值,基本数据类型
  -->
    <bean id="userserviceImpl" class="com.sue.service.UserServiceImpl">
        <property name="userDao" ref="mysqlImpl"/>
    </bean>

</beans>

测试

public class MyTest {
    public static void main(String[] args) {

ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("beans.xml");

UserServiceImpl user =(UserServiceImpl)ApplicationContext.getBean("userserviceImpl");

        user.getUser();

    }
}

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

4、IOC创建对象方式

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

    User.java

    public class User {
        private String name;
    
        public User() {
            System.out.println("User的无参构造");
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        public void show(){
            System.out.println("name="+name);
        }
    }
    
    

    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="user" class="com.sue.pojo.User">
            <property name="name" value="Genius Sue"/>
        </bean>
    
    
    </beans>
    

    测试类

    public class MyTest {
        public static void main(String[] args) {
            //User user = new User();
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
            User user = (User) applicationContext.getBean("user");
    
            user.show();
        }
    }
    
    

    结果我们可以发现,在调用show()方法之前,User对象已经通过无参构造初始化了。

  2. 假设我们要使用有参构造创建对象

    public class User {
        private String name;
    
        public User(String name) {
            this.name = name;
            System.out.println("User构造方法给name赋值"+this.name);
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void show() {
            System.out.println("name=" + this.name);
        }
    }
    
    1. 下标赋值

      <bean id="user" class="com.sue.pojo.User">
          <constructor-arg index="0" value="Sue01"/>
      </bean>
      
    2. 类型

      <!--    不推荐使用-->
      <bean id="user" class="com.sue.pojo.User">
          <constructor-arg type="java.lang.String" value="Sue02"/>
      </bean>
      
    3. 参数名

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

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了,不管你有没有使用。

5、spring配置

5.1、别名

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.sue.pojo.User">
        <property name="name" value="Genius Sue"/>
    </bean>


<!--  别名,如果添加了别名,我们也可以使用别名获取到这个对象  -->
    <alias name="user" alias="changeName"/>

</beans>

5.2、bean的配置

    <!--
     id:bean的标识符,要唯一,如果没有配置id,name就是默认标识符
     class:bean对象所对应的全限定名:包名+类名
     name:如果配置id,又配置了name,那么name是别名,而且name可以同时取多个别名,name可以设置多个别名,可以用逗号,分号,空格隔开
     -->

<bean id="user" class="com.sue.pojo.User" name="user2,user3;user4 user5">
    <property name="name" value="Genius Sue"/>
</bean>

5.3、import

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

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

  • 张三

  • 李四

  • 王五

  • 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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <import resource="beans.xml"/>
        <import resource="beans2.xml"/>
        <import resource="beans3.xml"/>
        
        
    </beans>
    

如果有一样的变量也会合并,使用的时候,直接使用总的配置就可以了。

6、依赖注入

6.1、构造器注入

前面已经说过了

6.2、set方式注入【重点】

依赖注入:set注入

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

  • 注入:beans对象的所有属性,由容器来注入

要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is

【环境搭建】

Address.java

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.java

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

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="address" class="com.sue.pojo.Address">
        <property name="address" value="福建"/>
    </bean>

    <bean id="student" class="com.sue.pojo.Student">
        <!--    第一种,普通值注入,value    -->
        <property name="name" value="Genius Sue"/>
        <!--    第二种,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="350425"/>
                <entry key="银行卡" value="606533"/>
            </map>
        </property>
        <!--    第六种,Set注入    -->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--    第七种,null值注入    -->
        <property name="wife">
            <null/>
        </property>
        <!--    第八种,properties注入    -->
        <property name="info">
            <props>
                <prop key="学号">202209131031</prop>
                <prop key="性别"></prop>
                <prop key="姓名">Genius Sue</prop>
            </props>
        </property>
    </bean>

</beans>

MyTest

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());
    }
}

6.3、拓展方式注入

我们可以使用

p命名空间

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

c命名空间

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

注入

User.java

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

    public String getName() {
        return name;
    }


    public User() {
    }

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

    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 +
                '}';
    }
}

  1. P命名注入:需要在头文件中加入约束文件
  2. 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命名空间注入,可以直接注入属性的值  -->
    <bean id="user" class="com.sue.pojo.User" p:name="Genius Sue" p:age="18"/>

<!--  c命名空间注入:通过构造器注入:construct  -->
    <bean id="user2" class="com.sue.pojo.User" c:name="Sue" c:age="666"/>

</beans>

测试:

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

注意:使用时记得导入约束

6.4、bean的作用域

image-20220504115307623

图片

  1. 单例模式(Spring默认机制)

    当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置:

    <bean id="user2" class="com.sue.pojo.User" c:name="Sue" c:age="666" scope="singleton"/>
    

    测试:

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("user-beans.xml");
        User user = context.getBean("user2", User.class);
        User user2 = context.getBean("user2", User.class);
        System.out.println(user.hashCode());
        System.out.println(user2.hashCode());
        System.out.println(user == user2); //ture
    }
    
  2. 原型模式:每次从容器中get的时候,都会产生一个新对象。

    当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:

    <bean id="user2" class="com.sue.pojo.User" c:name="Sue" c:age="666" scope="prototype"/>
    
  3. 其余的request、session、application这些个只能再web开发中使用到!

7、bean的自动装配

  • 自动装配是使用Spring满足bean依赖的一种方法

  • Spring会在上下文自动寻找,并自动给bean装配属性

在spring中有三种装配的方式

  1. 在xml中显式配置
  2. 在java中显式配置
  3. 隐式的bean发现机制和自动装配【重要】

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean
  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI

7.1、测试

环境搭建:一个人有两个宠物!

1、新建一个项目

2、新建两个实体类,Cat Dog 都有一个叫的方法

Cat.java

public class Cat {
    public void shut(){
        System.out.println("喵~");
    }
}

Dog.java

public class Dog {
    public void shut(){
        System.out.println("汪!");
    }
}

3、新建一个用户类 People

People.java

public class People {
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

test

public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        People people = context.getBean("people", People.class);

        people.getCat().shut();
        people.getDog().shut();
    }
}

7.2、ByName自动装配

<?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.sue.pojo.Dog"/>
    <bean id="cat" class="com.sue.pojo.Cat"/>

<!--
     byName:会自动在容器上下本中查找,和自己对象set方法后面的值对应的beanId
     例如 Dog可以使用dog和DOG但是DOG2这样的就是错误的
 -->
    <bean id="people" class="com.sue.pojo.People" autowire="byName">
        <property name="name" value="Genius Sue"/>
    </bean>

</beans>

7.3、ByType自动装配

<?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.sue.pojo.Dog"/>
    <bean id="cat" class="com.sue.pojo.Cat"/>

<!--
     byType:会自动在容器上下本中查找,和自己对象属性类型相同的bean
 -->
    <bean id="people" class="com.sue.pojo.People" autowire="byType">
        <property name="name" value="Genius Sue"/>
    </bean>

</beans>

小结:

  • 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/>

</beans>

@Autowired

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

使用Autowired我们可以不用编写set方法,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且类型符合byType

拓展:

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

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

举例:

​ 相同类型的bean,id=cat id=cat222,@Autowried先通过bytype,发现相同类型的cat,然后通过byName,发现了id=cat,装配成功,如果没有id=cat,失败

public class People {

//    如果显式的定义了Autowired的属性required = false说明属性可以为null
//    @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
//    @Qualifier不能单独使用
    @Autowired(required = false)
    @Qualifier(value = "cat222")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
	......
}
<bean id="dog" class="com.sue.pojo.Dog"/>
<bean id="dog222" class="com.sue.pojo.Dog"/>
<bean id="cat" class="com.sue.pojo.Cat"/>
<bean id="cat222" class="com.sue.pojo.Cat"/>
<bean id="people" class="com.sue.pojo.People"/>

@Resource注解

public class People {

    @Resource
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;
    ......
}

小结:

@Resource和@Autowired的区别

  • 都是用来自动装配的,都可以放到属性字段上
  • @Autowired通过byType的方式实现(ps:只根据byType匹配,不会匹配byName),而且必须要求这个对象存在!【常用】
  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到的情况就报错【常用】
  • 执行顺序不同:@Autowired通过byType的方式实现,@Resource默认通过byName的方式实现

8、使用注解开发

在spring4之后,要使用注解开发,必须要保证aop的包导入了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-saykdcpz-1663140677780)(D:\Desktop}Y~XZ}]61R7KEIIL{9PFY]B.png)]

使用注解需要导入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:component-scan base-package="com.sue.pojo"/>
    <context:annotation-config/>

</beans>
  1. bean

    //@Component 等价于 <bean id="user" class="com.sue.pojo.User"/>
    //@Component 组件,放在类上,说明这个类被Spring管理了,就是bean
    @Component
    public class User {
        public String name = "Genius Sue";
    }
    
    
  2. 属性如何注入

    @Component
    public class User {
    // @Value("Genius Sue") 相当于 <property name="name" value="Genius Sue"/>
        @Value("Genius Sue")
        public String name;
    }
    
  3. 衍生的注解

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

    • dao【@Repository】

    • service【@Service】

    • controller【@Controller】

      这四个注解功能都是一样的,都是代表某个类注册到spring,装配bean

  4. 自动装配

    @Resource
    @Autowired
    @Qualifier
    上面有介绍,这里不赘述
    
  5. 作用域

    //@Component 等价于 <bean id="user" class="com.sue.pojo.User"/>
    //@Component 组件
    @Component
    @Scope("prototype")
    public class User {
    // @Value("Genius Sue") 相当于 <property name="name" value="Genius Sue"/>
        @Value("Genius Sue")
        public String name;
    }
    
    
  6. 小结

    xml与注解:

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

    xml与注解最佳实践

    • xml用来管理bean

    • 注解只负责完成属性的注入

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

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

9、使用java的方式配置Spring

我们现在要完全不使用spring的xml配置了,全权交给java来做!

javaConfig是Spring的一个子项目,在Spring4之后,成了一个核心功能。

实体类User.java

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

    public String getName() {
        return name;
    }

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

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

配置类SueConfig.java

//这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
//@Configuration代表这是一个配置类,和beans.xml是一样的
@Configuration
@ComponentScan("com.sue.pojo")
@Import(Config.class)
public class SueConfig {


    //注册一个bean就相当于之前写的一个bean标签,
    //id = 方法名
    //方法的返回值相当于bean中的class属性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的对象
    }

}

Config.java

@Component
public class Config {
}

测试类

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,就只能通过AnnotationConfigApplicationContext上下文来获取容器,通过配置类class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(SueConfig.class);
        User getUser = context.getBean("getUser",User.class);
        System.out.println(getUser.getName());;

    }
}

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

10、代理模式

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

代理模式的分类:

  • 静态代理
  • 动态代理

10.1、静态代理

角色分析:

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

代码步骤:

  1. 接口【抽象出具体的功能】

    //租房这件事----代理的事
    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

    //房东
    public class Host implements Rent{
        @Override
        public void rent() {
            System.out.println("房东要出租房子");
        }
    }
    
  3. 代理角色

    //中介--代理角色
    public class Proxy implements Rent{
        private Host host;
        public Proxy() {
        }
        public Proxy(Host host) {
            this.host = host;
        }
        @Override
        public void rent() {
            seeHouse();
            host.rent();
            contract();
            fare();
        }
        //看房
        public void seeHouse(){
            System.out.println("中介带你看房");
        }
        //签合同
        public void contract(){
            System.out.println("签租赁合同");
        }
        //收中介费
        public void fare(){
            System.out.println("收中介费");
        }
    }
    
  4. 客户端访问代理角色

    public class Client {
        public static void main(String[] args) {
            //房东要租房子
            Host host = new Host();
            //代理,中介帮房东租房子,但是代理角色一般会有一些附属操作
            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{
        @Override
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        @Override
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        @Override
        public void update() {
            System.out.println("修改了一个用户");
        }
    
        @Override
        public void query() {
            System.out.println("查询一个用户");
        }
    }
    
    
  3. 代理角色

    public class UserServiceProxy implements UserService{
    
        private UserServiceImpl userService;
    
        public void setUserService(UserServiceImpl userService) {
            this.userService = userService;
        }
    
        @Override
        public void add() {
            log("add");
            userService.add();
        }
    
        @Override
        public void delete() {
            log("delete");
            userService.delete();
        }
    
        @Override
        public void update() {
            log("update");
            userService.update();
        }
    
        @Override
        public void query() {
            log("query");
            userService.query();
        }
    
    
        //增加一个日志的方法
        public void log(String msg){
            System.out.println("使用了" +msg+
                    "方法");
        }
    }
    
    
  4. 访问

    public class Client {
        public static void main(String[] args) {
            UserServiceImpl userService = new UserServiceImpl();
    
            UserServiceProxy userServiceProxy = new UserServiceProxy();
            userServiceProxy.setUserService(userService);
    
            userServiceProxy.add();
        }
    }
    

10.3、动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分成两个类:基于接口的动态,基于类的动态代理
    • 基于接口–JDK动态代理【我们在这里使用】
    • 基于类:cglib
    • java字节码实现:javasist

需要了解两个类

  • Proxy:代理
  • InvocationHandler:调用处理程序

动态代理的好处:

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

ProxyInvocationHandle.java

//我们会用这个类自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Object target;

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

    //生成得到代理类
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        //动态代理的本质,就是使用反射机制实现
        Object invoke = method.invoke(target, args);
        return invoke;
    }

    public void log(String msg){
        System.out.println("执行了" + msg +
                "方法");
    }
}

验证:

public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();

        //代理角色,不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        //设置要代理的对象
        pih.setTarget(userService);

        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();
        proxy.add();
    }
}

一个动态代理 , 一般代理某一类业务 , 一个动态代理可以代理多个类,代理的是接口!

11、AOP

11.1、什么是AOP

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

image-20220511211111236

11.2、AOP在spring中的作用

提供声明式事务,允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点,如:日志,安全,缓存,事务等等。。。
  • 切面(Aspect):横切关注点,被模块化的特殊对象。即,它是一个类
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法
  • 目标(Target):被通知对象
  • 代理(Proxy):向目标对象应用通知之后创建的对象
  • 切入点(PointCut):切面通知 执行的“地点”的定义
  • 连接点(JoinPoint):与切入点匹配的执行点

image-20220511211921345

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5中类型的Advice

image-20220511212139453

即Aop在不改变原有代码的情况下,去增加新的功能

11.3、使用spring实现AOP

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

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.9.1</version>
</dependency>

方式一:使用spring的api接口【主要springapi接口实现】

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}
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("查询了一个用户");
    }
}
public class Log implements MethodBeforeAdvice {

    //method:要执行的目标对象的方法,
    //args: 参数
    //target: 目标对象
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    //returnValue 返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为->"+returnValue);
    }
}

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

    <!--  注册bean  -->
    <bean id="userServiceImpl" class="com.sue.service.UserServiceImpl"/>
    <bean id="log" class="com.sue.log.Log"/>
    <bean id="afterlog" class="com.sue.log.AfterLog"/>

    <!--    方式一:使用原生的Spring API接口-->
    <!--  配置AOP:需要导入AOP的约束  -->
    <aop:config>
        <!--    切入点:我们需要在哪个地方执行方法
        expression:表达式
        execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?)
        其中:返回类型模式、方法名模式、参数模式是必选项
        -->
        <aop:pointcut id="pointcut" expression="execution(* com.sue.service.UserServiceImpl.*(..))"/>
        <!--  执行环绕增加  -->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>
    
</beans>

测试

public class Mytest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userservice = context.getBean("userServiceImpl", UserService.class);
        userservice.add();
    }
}

直接结果

com.sue.service.UserServiceImpl的add被执行了
增加了一个用户
执行了add方法,返回结果为->null

参考博客:(10条消息) execution()表达式_代码无常的博客-CSDN博客_execution()

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

public class DiyPointCut {

    public void before(){
        System.out.println("方法执行前");
    }

    public void after(){
        System.out.println("方法执行后");
    }
}

beans.xml 注释掉方式一,新增方式二

    <!--  方式二:自定义类  -->
    <bean id="diy" class="com.sue.diy.DiyPointCut"/>
    
    <aop:config>
        <!--  自定义切面,ref要引用的类  -->
        <aop:aspect ref="diy">
            <!--      切入点      -->
            <aop:pointcut id="point" expression="execution(* com.sue.service.UserServiceImpl.*(..))"/>
            <!--      通知      -->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

测试类不变,结果如下

方法执行前
增加了一个用户
方法执行后

方式三:使用注解实现

//使用注解方式实现AOP

@Aspect//标准这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.sue.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }
    @After("execution(* com.sue.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理的切入点
    @Around("execution(* com.sue.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");
        Object proceed = joinPoint.proceed();//获得签名
        System.out.println("环绕后");
        System.out.println(joinPoint.getSignature());
        System.out.println(proceed);
    }
}

beans.xml注释之前的两种方式,新增配置

   <!--  方式三:使用注解实现  -->
    <bean id="annotationPointCut" class="com.sue.diy.AnnotationPointCut"/>
    <!--    开启注解支持 jdk(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy/>

测试类不变,结果如下

方法执行前
增加了一个用户
方法执行后

12、整合mybatis

步骤:

  1. 导入jar包

    • junit

    • mybatis

    • mysql数据库

    • spring相关

    • aop织入

    • mybatis-spring【new】

          <dependencies>
              <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>8.0.30</version>
              </dependency>
              <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
              <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis</artifactId>
                  <version>3.5.10</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-jdbc</artifactId>
                  <version>5.3.22</version>
              </dependency>
              <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>
              </dependency>
              <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-webmvc</artifactId>
                  <version>5.3.22</version>
              </dependency>
              <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>4.13.2</version>
              </dependency>
          </dependencies>
      
  2. 编写配置文件

  3. 测试

12.1、回忆mybatis

  1. 编写实体类

    @Data
    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>
        
        <typeAliases>
            <package name="com.sue.pojo"/>
        </typeAliases>
        
        <!--    environment 元素体中包含了事务管理和连接池的配置-->
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        
        <mappers>
            <mapper class="com.sue.mapper.UserMapper"/>
        </mappers>
        
    </configuration>
    
  3. 编写接口

    public interface UserMapper {
        public List<User> selectUser();
    }
    
  4. 编写Mapper.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">
    <!--configuration 核心配置文件-->
    <mapper namespace="com.sue.mapper.UserMapper">
     
        <select id="selectUser" resultType="user">
            select *
            from mybatis.user;
        </select>
    
    </mapper>
    
  5. 测试

    public class MyTest {
        @Test
        public void test() throws IOException {
            String resources = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resources);
    
    
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.selectUser();
            for (User user : users) {
                System.out.println(user);
            }
        }
    }
    

12.2、mybatis-spring

官方文档:mybatis-spring –

步骤(在上面的基础上改造)

  1. 编写数据源配置

  2. sqlSessionFactory

  3. SqlSessionTemplate

  4. 需要给接口类加实现类【】

  5. 将自己写的实现类,注入到Spring中,测试使用即可

    配置文件spring-mapper.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">
    
        <!--  DataSource:使用spring的数据源替换mybatis的配置
              这里我们使用spring提供的: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?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8"/>
            <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配置文件    -->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:com/sue/mapper/UserMapper.xml"/>
        </bean>
    
        <!--  SqlSessionTemplate:就是我们使用的sqlSession  -->
        <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <!--    只能使用构造器注入sqlSessionFactory,因为它没有set方法    -->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
    </beans>
    

    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>
        
        <typeAliases>
            <package name="com.sue.pojo"/>
        </typeAliases>
        
    </configuration>
    
  6. 实现接口

    UserMapperImpl.java

    public class UserMapperImpl implements UserMapper{
    //    我们原来所有的操作都使用sqlSession来执行,现在都使用SqlSessionTemplate
        private SqlSessionTemplate sqlSessionTemplate;
    
        public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
            this.sqlSessionTemplate = sqlSessionTemplate;
        }
    
        @Override
        public List<User> selectUser() {
            UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
            return  mapper.selectUser();
        }
    }
    
  7. 配置bean

    这里不直接在spring-dao.xml中配置,为了保持spring-dao.xml的干净整洁,因为这个配置文件后续基本不变,新增再下面这里操作即可!

    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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <import resource="spring-mapper.xml"/>
    
        <bean id="userMapperImpl" class="com.sue.mapper.UserMapperImpl">
            <property name="sqlSessionTemplate" ref="sqlSession"/>
        </bean>
    
    </beans>
    
  8. 测试

    public class MyTest {
        @Test
        public void test() throws IOException {
    
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
            List<User> users = userMapper.selectUser();
            for (User user : users) {
                System.out.println(user);
            }
        }
    }
    
    

另外一种SqlSessionDaoSupport实现

新增一个UserMapperImpl2.java

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

注入spring applicationContext.xml配置文件新增如下配置

<bean id="userMapperImpl2" class="com.sue.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

测试:

public class MyTest {
    @Test
    public void test() throws IOException {

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

        UserMapper userMapper = context.getBean("userMapperImpl2", UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

13、声明式事务

13.1、回顾事务

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

事务ACID原则:

  • 原子性(atomicity)
    • 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用
  • 一致性(consistency)
    • 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
  • 隔离性(isolation)
    • 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏
  • 持久性(consistency)
    • 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中

13.2、spring中事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中,进行事务的管理

思考:为什么需要事务?

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

声明式事务

spring核心配置

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--  DataSource:使用spring的数据源替换mybatis的配置
          这里我们使用spring提供的: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?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8"/>
        <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配置文件    -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/sue/mapper/UserMapper.xml"/>
    </bean>

    <!--  SqlSessionTemplate:就是我们使用的sqlSession  -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--    只能使用构造器注入sqlSessionFactory,因为它没有set方法    -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--  配置声明式事物  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>

    <!--  结合AOP实现事物的织入  -->
    <!--  配置事物通知:  -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--    给哪些方法配置事物    -->
        <!--    配置事务的传播特性  propagation  -->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--  配置事物切入  -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.sue.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

spring事务的7种传播特性:

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

  • propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
  • propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
  • propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
  • propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
  • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
  • propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

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

接口新增功能

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


    public int addUser(User user);

    public int deleteUser(int id);
}

实现类

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUser() {

        User user = new User(5,"小郭","123456");

        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);
    }
}

Mapper.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">
<!--configuration 核心配置文件-->
<mapper namespace="com.sue.mapper.UserMapper">
 
    <select id="selectUser" resultType="user">
        select *
        from mybatis.user;
    </select>

    <insert id="addUser" parameterType="user">
        insert into mybatis.user(id, name, pwd) value (#{id}, #{name}, #{pwd})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete
        from mybatis.user
        where id=#{id};
    </delete>

</mapper>

测试类

public class MyTest {
    @Test
    public void Test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

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

        for (User user : users) {
            System.out.println(user);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Genius-Sue

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值