Spring入门

Spring

1、Spring

1.1、Spring 简介

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

官网:https://spring.io/projects/spring-framework

官网下载地址:http://repo.spring.io/release/org/springframework/spring

GitHub:https://github.com/spring-projects/spring-framework

maven:

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

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.15</version>
</dependency>

1.2、 优点

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

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

1.3、组成

在这里插入图片描述

1.4、 拓展

  • Spring Boot
    • 一个快速开发的脚手架。
    • 基于SpringBoot可以快速的开发单个微服务。
    • 约定大于配置!
  • Spring Cloud
    • SpringCloud 是基于SpringBoot实现的

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

2、 IOC理论推导

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

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

dao

//固定死所用的实现类
// private UserDao userDao = new UserDaoImpl;
private UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}

Service变化

//之前调用dao层
// UserService userservice = new UserServiceImpl();

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

这种思想,从本质上解决了问题,我们不用再去管理对象的创建了,系统的耦合性打打降低,可以更加专注的在业务都实现上!这是IOC的原型!

2.1、IOC理解

Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想。在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内部直接控制。如何理解好Ioc呢?理解好Ioc的关键是要明确“谁控制谁,控制什么,为何是反转(有反转就应该有正转了),哪些方面反转了”,那我们来深入分析一下:

●谁控制谁,控制什么:传统Java SE程序设计,我们直接在对象内部通过new进行创建对象,是程序主动去创建依赖对象;而IoC是有专门一个容器来创建这些对象,即由Ioc容器来控制对 象的创建;谁控制谁?当然是IoC 容器控制了对象;控制什么?那就是主要控制了外部资源获取(不只是对象包括比如文件等)。

●为何是反转,哪些方面反转了:有反转就有正转,传统应用程序是由我们自己在对象中主动控制去直接获取依赖对象,也就是正转;而反转则是由容器来帮忙创建及注入依赖对象;为何是反转?因为由容器帮我们查找及注入依赖对象,对象只是被动的接受依赖对象,所以是反转;哪些方面反转了?依赖对象的获取被反转了。

用图例说明一下,传统程序设计,都是主动去创建相关对象然后再组合起来:

请添加图片描述

​ 传统应用程序示意图

当有了IoC/DI的容器后,在客户端类中不再主动去创建这些对象了:

在这里插入图片描述

​ 有IoC/DI容器后程序结构示意图

2.2、IoC能做什么

IoC 不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合、更优良的程序。传统应用程序都是由我们在类内部主动创建依赖对象,从而导致类与类之间高耦合,难于测试;有了IoC容器后,把创建和查找依赖对象的控制权交给了容器,由容器进行注入组合对象,所以对象与对象之间是 松散耦合,这样也方便测试,利于功能复用,更重要的是使得程序的整个体系结构变得非常灵活。

其实IoC对编程带来的最大改变不是从代码上,而是从思想上,发生了“主从换位”的变化。应用程序原本是老大,要获取什么资源都是主动出击,但是在IoC/DI思想中,应用程序就变成被动的了,被动的等待IoC容器来创建并注入它所需要的资源了。

2.3、IOC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说的

法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,

控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息涩和现实分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接可以注

解的形式定义在实现类中,从而达到了零配置的目的。

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

3、hellospring

bean配置

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">

    <!-- 使用Spring来创建对象,这些在Spring都称之为Bean -->
    <bean id="hello" class="com.bnzr.pojo.Hello">
        <!--value="{用于对基本类型进行赋值}" 
            ref="{其他创建好的类型用ref进行赋值如其他对象如:ref:"str"}"-->
        <property name="str" value="Spring" />
    </bean>


    <!-- more bean definitions for services go here -->

</beans>

编写POJO

package com.bnzr.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 + '\'' +
                '}';
    }
}

测试

import com.bnzr.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    @Test
    public  void helloTest(){
        System.out.println("test1==================");
        //获取spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //对象现在都在Spring中进行管理,使用时直接获取就可以。
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

思考问题

  • User对象是谁创建的?

    User对象说由Spring创建的

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

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

这个过程就叫控制反转:

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

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

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

IoC是一种编程思想,由主动点编程编程被动的接收。

可以通过new ClassPathApplicationContext去浏览底层源码。

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

4、 IoC创建对象的方式

  1. constructor-arg:通过构造函数注入。
    property:通过set对应的方法注入。

  2. 使用无参构造创建对象。

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

    1. 下标赋值

          <bean id="user" class="com.bnzr.pojo.User">
              <constructor-arg index="0" value="测试的"/>
          </bean>
      
    2. 类型

      <!--通过类型去创建,不建议使用-->
      <bean id="userT" class="com.xia.pojo.UserT">
          <constructor-arg type="java.lang.String" value="糖果C"></constructor-arg>
      </bean>
      
    3. 直接通过参数名

      <!--重点掌握这一种方法-->
      <bean id="user" class="com.bnzr.pojo.User">
          <constructor-arg name="name" value="测试的一个6"/>
      </bean>
      

    总结:在配置文件加载的时候,容器中管理的所有的对象就已经初始化了,且每个管理的对象只创建了一个。

5、 Spring配置

5.1、 别名

<!--别名,如果添加了别名,我们也可以用别名获取到这个对象(原始的id与别名都可以获取的到)-->
<alias name="user" alias="testUser"></alias>

5.2、 Bean的配置

<!--
    id: bean 的唯一标识符,也就是相当于我们学的对象名
    class: bean 对象所对应的全限定名: 包名 + 类名
    name: 也是别名,而且name 可以同时取多个别名
    -->
<bean id="userT" class="com.xia.pojo.UserT" name="user2 u2,us2;uss2"></bean>

5.3、 import

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

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

  • 张三 beans.xml

  • 李四 beans1.xml

  • 王五

  • applicationContext.xml

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

当不同的xml配置导入时,同Id的bean后面的xml会覆盖前面的xml

6、 依赖注入

6.1、 构造器注入

前面已经说过了

6.2、 Set方法注入

  • 依赖注入:Set注入!
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入!

【注入例子】

引用类型

package com.bnzr.pojo;


public class Address {
    private String address;

    public Address() {
    }

    public Address(String address) {
        this.address = address;
    }

    public String getAddress() {
        return address;
    }

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

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

主实体类

package com.bnzr.pojo;

import java.util.*;

public class Student {
    private String name;
    private Address address;
    private String[] book;
    private List<String> hobbies;
    private Map<String, Object> 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[] getBook() {
        return book;
    }

    public void setBook(String[] book) {
        this.book = book;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

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

    public void setCard(Map<String, Object> 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 +
                ", book=" + Arrays.toString(book) +
                ", hobbies=" + hobbies +
                ", 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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.bnzr.pojo.Address">

    </bean>

    <bean id="student" class="com.bnzr.pojo.Student">
        <!-- 基本类型直接注入值-->
        <property name="name" value="彼岸"/>
        <!-- bean注入-->
        <property name="address" ref="address"/>
        <!-- 数组注入-->
        <property name="book">
            <array>
                <value>《java基础》</value>
                <value>《java架构》</value>
                <value>《python基础》</value>
            </array>
        </property>
        <!-- List注入-->
        <property name="hobbies">
            <list>
                <value>上班</value>
                <value>挣钱</value>
                <value></value>
            </list>
        </property>
        <!-- Map注入-->
        <property name="card">
            <map>
                <entry key="" value="1"/>
                <entry key="" value="0"/>
            </map>
        </property>
        <!-- Set注入-->
        <property name="games">
            <set>
                <value>开发</value>
                <value>测试</value>
                <value>运维</value>
            </set>
        </property>
        <!-- Null注入-->
        <property name="wife">
            <null/>
        </property>
        <!-- Properties注入-->
        <property name="info">
            <props>
                <prop key="driver">com.mysql.jdbc.Driver</prop>
                <prop key="url">localhost:3306/mybatis</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

</beans>

测试类

import com.bnzr.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class diTest {
    @Test
    public void diTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
}
/**
Student{name='彼岸', 
address=Address{address='null'}, 
book=[《java基础》, 《java架构》, 《python基础》], 
hobbies=[上班, 挣钱, 玩], 
card={是=1, 否=0}, 
games=[开发, 测试, 运维], 
wife='null', 
info={password=123456, url=localhost:3306/mybatis, driver=com.mysql.jdbc.Driver, username=root}}

*/

6.3、 拓展方式注入

我们可以使用P命名空间和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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

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

    <!--C命名空间注入,可以通过构造器注入:construct-args-->
    <bean id="user2" class="com.bnzr.pojo.User" c:age="20" c:name="c的注入"/>
</beans>

测试:

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

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

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

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

6.4、 bean的作用域

ScopeDescription
singleton(默认)将每个 Spring IoC 容器的单个 bean 定义范围限定为单个对象实例。
prototype将单个 bean 定义的作用域限定为任意数量的对象实例。
request将单个 bean 定义的范围限定为单个 HTTP 请求的生命周期。也就是说,每个 HTTP 请求都有一个在单个 bean 定义后面创建的 bean 实例。仅在可感知网络的 Spring ApplicationContext中有效。
session将单个 bean 定义的范围限定为 HTTP Session的生命周期。仅在可感知网络的 Spring ApplicationContext上下文中有效。
application将单个 bean 定义的范围限定为ServletContext的生命周期。仅在可感知网络的 Spring ApplicationContext上下文中有效。
websocket将单个 bean 定义的范围限定为WebSocket的生命周期。仅在可感知网络的 Spring ApplicationContext上下文中有效。
  1. 单例模式(Spring默认机制)

    <bean id="user" class="com.bnzr.pojo.User" p:age="18" p:name="美丽的小姐" scope="singleton"></bean>
    
  2. 原型模式:每一次从容器中get的时候,都会产生一个新的对象

    <bean id="user" class="com.bnzr.pojo.User" p:age="18" p:name="美丽的小姐" scope="prototype"></bean>
    
  3. 其余的request、session、application,这些只能在web开发中使用到!

7、 Bean的自动装配

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

在Spring中有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示配置
  3. 隐式的自动装配bean

7.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.bnzr.pojo.Cat"/>
    <bean id="dog" class="com.bnzr.pojo.Dog"/>

    <bean id="people" class="com.bnzr.pojo.People">
        <property name="name" value="猫奴"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>

</beans>

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.bnzr.pojo.Cat"/>
    <bean id="dog" class="com.bnzr.pojo.Dog"/>

    <!--byname:会自动在容器上下文中查找,要保证上面bean id中的参数名和,people用户类中set方法中,除了set,第一个字母小写后的参数名一致-->
    <bean id="people" class="com.bnzr.pojo.People" autowire="byName">
        <property name="name" value="猫奴"/>
    </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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.bnzr.pojo.Cat"/>
    <bean id="dog" class="com.bnzr.pojo.Dog"/>

    <!--byType:会自动在容器上下文查找,和自己对象属性类型相同的bean!(需要装配对象的bean全局唯一)-->
    <bean id="people" class="com.bnzr.pojo.People" autowire="byType">
        <property name="name" value="猫奴"/>
    </bean>

</beans>

小结:

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

7.4、 使用注解实现自动装配

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

要使用注解须知:

  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
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
        <context:annotation-config/>
    </beans>
    

1. @Autowired

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

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

科普:

//字段标记了这个注解,说明这个字段可以为null; 	
@Nullable
    private String name; 
 //显示定义了required为false,说明这个字段可以为null; 	
    @Autowired(required = false)
    private Cat cat;

测试代码

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

    <!--开启注解支持-->
    <context:annotation-config/>

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

</beans>

people

package com.bnzr.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;

public class People {
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    @Nullable
    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 + '\'' +
                '}';
    }
}

mytest

import com.bnzr.pojo.People;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        People people = context.getBean("people", People.class);
        people.getDog().shout();
        people.getCat().shout();
    }
}

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

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

    <!--开启注解支持-->
    <context:annotation-config/>

    <bean id="cat11" class="com.bnzr.pojo.Cat"/>
    <bean id="cat22" class="com.bnzr.pojo.Cat"/>
    <bean id="dog11" class="com.bnzr.pojo.Dog"/>
    <bean id="dog22" class="com.bnzr.pojo.Dog"/>
    <bean id="people" class="com.bnzr.pojo.People"/>

</beans>

people

public class People {
    @Autowired
    @Qualifier(value = "cat22")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog11")
    private Dog dog;
    @Nullable
    private String name;

@Resource 注解

import javax.annotation.Resource;
public class People {
    @Resource
    private Dog dog;
    @Resource(name = "cat2")
    private Cat cat;
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public Cat getCat() {
        return cat;
    }
    public void setCat(Cat cat) {
        this.cat = cat;
    }
}

小结:

@Autowired 和 @Resource 的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired先通过byType的方式实现,找不到再通byName注入,还早不到通过过实现@Qualifier查找
  • @Resource 先通过byName的方式实现,找不到再通过byType实现,如果都找不到的情况下,就会报错
  • 执行顺序不同:@Autowired先通过byType,@Resource

8、 使用注解开发

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

使用注解需要导入context约束,增加注解的支持

  1. bean

  2. 属性如何注入

    package com.bnzr.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    //相当于<bean id="user" class="com.bnzr.pojo.User"></bean>
    @Component
    public class User {
    
        相当于<property name="name" value="狂徒张三"></property>
        @Value("狂徒张三")
        public String name;
    
    
        //@Value("狂徒张三")效果与在属性定义上一致
        public void setName(String name) {
            this.name = name;
        }
    }
    
    
  3. 衍生的注解

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

    • dao @Repository

    • service @Service

    • controller @Controller

      这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean

  4. 自动装配

    - @Autowired
    自动装配通过类型,名字。
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
    - @Nullable
    字段标记了这个注解,说明这个字段可以为null;
    - @Resource
    自动装配通过名字,类型。 
    
  5. 作用域

    package com.bnzr.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component;
    
    //相当于<bean id="user" class="com.bnzr.pojo.User"></bean>
    @Component
    //标注为单例模式(@Scope("prototype")是原型模式)
    @Scope("singleton")
    public class User {
    
        相当于<property name="name" value="狂徒张三"></property>
        @Value("狂徒张三")
        public String name;
    
    
        //@Value("狂徒张三")效果与在属性定义上一致
        public void setName(String name) {
            this.name = name;
        }
    }
    
    
  6. 小结

    xml与注解:

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

    xml与注解最佳实践:

    • xml用来管理bean。

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

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

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

9、 使用Java的方式配置Spring

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

JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!

实体类

package com.bnzr.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

//相当于<bean id="user" class="com.bnzr.pojo.User"></bean>
@Component
//标注为单例模式()
@Scope("singleton")
public class User {

    相当于<property name="name" value="狂徒张三"></property>
    @Value("狂徒张三")
    public String name;


    //@Value("狂徒张三")效果与在属性定义上一致
    public void setName(String name) {
        this.name = name;
    }
}

配置文件类

package com.bnzr.config;

import com.bnzr.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

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

//也可以进行融合
@Import(WangConfig.class)

public class bnzrConfig {

    /*注册一个bean,就相当于我们写一个bean标签
    这个方法的名字,就相当于bean标签中的id属性
    这个方法的返回值,就相当于bean标签中的class属性*/
    @Bean
    public User getUser(){
        return new User();
    }
}

测试类!

import com.bnzr.config.bnzrConfig;
import com.bnzr.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    @Test
    public void UserTest(){
        //如果完全使用了配置类方法去做,我们就只能通过AnnotationConfig上下文去获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(bnzrConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.name);
    }
}

这种纯Java的配置在SpringBoot随处可见

10、 代理模式

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

10.1、 静态代理

角色分析:

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

代码步骤:

  1. 接口

    public interface Rent {
        void rent();
    }
    
  2. 真实角色

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

    public class Proxy implements Rent {
        private Master master;
        public Master getMaster() {
            return master;
        }
        public void setMaster(Master master) {
            this.master = master;
        }
        public void rent() {
            master.rent();
        }
        public void seeHouse(){
            System.out.println("看房");
        }
        public void fee(){
            System.out.println("收中介费");
        }
        public void heTong(){
            System.out.println("签合同");
        }
    }
    
  4. 客户端访问代理角色

    public class MyTest {
        public static void main(String[] args) {
            Master master = new Master();
            Proxy proxy = new Proxy();
            proxy.setMaster(master);
            proxy.seeHouse();
            proxy.rent();
            proxy.heTong();
            proxy.fee();
        }
    }
    

代理模式的好处:

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

缺点:

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

10.2、 加深理解

  1. 接口

    public interface UserService {
        void add();
        void delete();
        void update();
        void query();
    }
    
  2. Service层

    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 UserServiceImpl getUserService() {
            return 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("打印"+msg+"方法日志");
        }
    }
    
  4. 客户端

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

10.3、 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的!
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口 — JDK 动态代理
    • 基于类: cglib
    • java字节码实现: javasist

需要了解两个类: Proxy: 提供创建动态代理类的实例的静态方法, InvocationHandler: 调用处理程序实现接口

动态代理的好处:

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

抽象接口

package com.bnzr.pojo;

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

真实角色

package com.bnzr.pojo;

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("查询用户");
    }
}

动态代理类

package com.bnzr.pojo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用这个类,自动生成代理类
 */
public class ProxyInvocationHandler implements InvocationHandler {

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

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

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

    /**
     * 处理代理实力,并返回结果
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    /**
     * 打印执行方法
     * @param msg
     */
    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }
}

测试

package com.bnzr.pojo;

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可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

在这里插入图片描述

11.2、 AOP在Spring中的作用

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

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

在这里插入图片描述

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

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

11.3、 使用Spring实现AOP

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

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

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

  1. 实现AfterReturningAdvice接口

    package com.bnzr.log;
    
    import org.springframework.aop.AfterReturningAdvice;
    
    import java.lang.reflect.Method;
    
    public class AfterLog implements AfterReturningAdvice {
        /**
         *方法完成后执行
         * @param returnValue 返回值
         * @param method      要执行的目标对象方法
         * @param args        参数
         * @param target      目标对象
         * @throws Throwable
         */
        @Override
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("执行了"+target.getClass().getName()+"的一个"+method.getName()+"方法,结果为"+returnValue);
        }
    }
    
  2. 实现MethodBeforeAdvice接口

    package com.bnzr.log;
    
    import org.springframework.aop.MethodBeforeAdvice;
    
    import java.lang.reflect.Method;
    
    public class Log implements MethodBeforeAdvice {
    
        /**
         *方法完成前执行
         * @param method 要执行的目标对象方法
         * @param args   参数
         * @param target 目标对象
         * @throws Throwable
         */
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println(target.getClass().getName()+"的一个"+method.getName()+"方法");
        }
    }
    
  3. 注册配置文件

    <?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
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--注册bean-->
        <bean id="userService" class="com.bnzr.service.UserServiceImpl"/>
        <bean id="log" class="com.bnzr.log.Log"/>
        <bean id="afterlog" class="com.bnzr.log.AfterLog"/>
    
        <!--方式一:使用原生Spring API接口-->
        <!--配置AOP:需要导入aop的约束-->
        <aop:config>
            <!--切入点:expression是一个表达式,execution(是要执行的位置)-->
            <aop:pointcut id="pointcut" expression="execution(* com.bnzr.service.UserServiceImpl.*(..))"/>
    
            <!--执行环绕增加!-->
            <!--advice-ref 使用那个类增强; pointcut-ref:切入的位置-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
        </aop:config>
    </beans>
    
  4. 测试

    import com.bnzr.service.UserService;
    import com.bnzr.service.UserServiceImpl;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
        @Test
        public void aopTest(){
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //动态代理的是接口而不是实现类
            //相当于返回的是被创建的代理类
            //代理类与被代理类都实现的是UserService接口
            //所以新生成的代理类只能向上转型为接口类型,不能同等级强转给UserServiceImpl
    
            UserService userService = context.getBean("userService", UserService.class);
            userService.add();
        }
    }
    

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

定义接口

package com.bnzr.diy;

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

配置

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

    <!--注册bean-->
    <bean id="userService" class="com.bnzr.service.UserServiceImpl"/>

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

方式三: 使用注解实现

编写AnnotationPointCut类

package com.bnzr.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * 使用注解方式实现AOP
 */


//标注这个类是一个切面
@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.bnzr.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===执行前===");
    }

    @After("execution(* com.bnzr.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===执行之后===");
    }

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

        joinPoint.proceed();
        System.out.println("环绕后");
    }

    /**
     * 结果:
     * 环绕前
     * 方法签名;void com.bnzr.service.UserService.add()===执行前===
     * 新增一个用户
     * ===执行之后===
     * 环绕后ss
     */
}

配置文件

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

    <!--注册bean-->
    <bean id="userService" class="com.bnzr.service.UserServiceImpl"/>


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

12、 整合Mybaits

步骤:

  1. 导入相关jar包

    1. spring-webmvc
    2. spring-jdbc
    3. aspectjweaver
    4. mysql
    5. mybatis
    6. mybatis-spring[新包]
    7. junit
     <dependencies>
         <!-- spring核心包 -->
         <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.3.14</version>
            </dependency>
         <!-- spring连接数据库包 -->
                 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.16</version>
            </dependency>
    
            <!-- aop包 -->
            <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.8</version>
            </dependency>
         
            <!--Mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.27</version>
            </dependency>
    
            <!-- mybatis包 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.9</version>
            </dependency>
    		<!-- mybatis整合spring包 -->
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.7</version>
            </dependency>
    
         	 <!-- juint包 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <!--            <scope>test</scope>-->
            </dependency>
        </dependencies>
    
  2. 编写配置

  3. 文件测试

12.1 回忆mybatis

1.编写实体类
2.编写核心配置文件
3.编写接口
4.编写Mapper.xml文件
5.测试

12.2、 Mybatis-Spring

官方文档:http://mybatis.org/spring/zh/index.html

MyBatis-Spring 功能就是将MyBatis 代码无缝地整合到 Spring 中。

整体的整合步骤就是:

  1. 编写数据源配置
  2. sqlSessionFactory
  3. sqlSessionTemplat
  4. 给接口加实现类
  5. 将实现类注入spring中
  6. 测试使用

12.3、实现

  1. 编写Spring配置文件

    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
            http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!--DataSource:使用Spring的数据源替换Mybatis的配置
            使用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://10.2.38.1:3338/jdbc?useUnicode=true&amp;characterEncoding-utf8&amp;useSSL=true"/>
            <property name="username" value="root"/>
            <property name="password" value="P@ssw0rd"/>
        </bean>
        <!--sqlSessionFactory
            取代手动编写获取SqlSessionFactory对象
        -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!--绑定mybatis配置-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <!--设置mapper映射-->
            <property name="mapperLocations" value="classpath:com/bnzr/mapper/*.xml"/>
        </bean>
        <!--SqlSessionTemplate
                与之前使用的SqlSession相同
        -->
        <bean id="SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <!--只能使用构造器方法注入参数,因为没有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
        <bean id="userMapper" class="com.bnzr.mapper.UserMapperImpl">
            <property name="sqlSessionTemplate" ref="SqlSessionTemplate"/>
        </bean>
    </beans>
    
  2. pojo

    package com.bnzr.pojo;
    
    import lombok.Data;
    
    @Data
    public class User {
        private int id;
        private String name;
        private String pwd;
        private String email;
        private String birthday;
    
    }
    
  3. 接口类

    package com.bnzr.mapper;
    
    import com.bnzr.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
        public List<User> selectUser();
    }
    
    
  4. Mybatis实现接口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.bnzr.mapper.UserMapper">
    
        <select id="selectUser" resultType="user">
            select * from users
        </select>
    </mapper>
    
  5. 需要给接口加实现类

    package com.bnzr.mapper;
    
    import com.bnzr.pojo.User;
    import org.mybatis.spring.SqlSessionTemplate;
    
    import java.util.List;
    
    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();
        }
    }
    
    
  6. 测试

    import com.bnzr.mapper.UserMapper;
    import com.bnzr.pojo.User;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import java.io.IOException;
    
    
    public class MyTest {
        @Test
        public void UserTest() throws IOException {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
            for (User user : userMapper.selectUser()) {
                System.out.println(user.toString());
            }
        }
    }
    
    

12.4、继承SqlSessionDaoSupport 实现

实现类

package com.bnzr.mapper;

import com.bnzr.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

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

配置文件

<bean id="userMapperImplTwo" class="com.bnzr.mapper.UserMapperImplTwo">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

测试

import com.bnzr.mapper.UserMapper;
import com.bnzr.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;


public class MyTest {
    @Test
    public void UserTest() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = context.getBean("userMapperImplTwo", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user.toString());
        }
    }
}

13、 声明式事务

13.1.回顾事务

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

事务的ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作同一个资源,互相隔离,防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中

13.2、 Spring中的事务管理

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

为什么需要事务?

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

配置核心;

  <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--结合AOP实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <tx:attributes>
            <!--事务的传播特性,新特性:propagation 默认选择REQUIRED-->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <!--read-only="true" 只读-->
            <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.bnzr.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

UserMapper:

package com.bnzr.mapper;

import com.bnzr.pojo.User;

import java.util.List;

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

    public int addUser(User user);

    public int deleteUser(int id);
}

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.bnzr.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from users
    </select>
    
    <insert id="addUser" parameterType="user">
        insert into users (id, name, password)
        values (#{id},#{name},#{password});
    </insert>

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

UserMapperImpl:

package com.bnzr.mapper;

import com.bnzr.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
        User user = new User(9, "测试", "123456","12121@123","1999-01-01");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(9);
        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);
    }
}

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

    <!--DataSource:使用Spring的数据源替换Mybatis的配置
        使用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://10.2.38.1:3338/jdbc?useUnicode=true&amp;characterEncoding-utf8&amp;useSSL=true"/>
        <property name="username" value="root"/>
        <property name="password" value="P@ssw0rd"/>
    </bean>
    <!--sqlSessionFactory
        取代手动编写获取SqlSessionFactory对象
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--设置mapper映射-->
        <property name="mapperLocations" value="classpath:com/bnzr/mapper/*.xml"/>
    </bean>
    <!--SqlSessionTemplate
            与之前使用的SqlSession相同
    -->
    <bean id="session" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器方法注入参数,因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--结合AOP实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <tx:attributes>
            <!--事务的传播特性,新特性:propagation 默认选择REQUIRED-->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <!--read-only="true" 只读-->
            <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.bnzr.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

MyTest

import com.bnzr.mapper.UserMapper;
import com.bnzr.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class MyTest {
    @Test
    public void userTest(){
        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);
        }
    }
}

ybatis.spring.SqlSessionFactoryBean">










<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--给哪些方法配置事务-->
    <tx:attributes>
        <!--事务的传播特性,新特性:propagation 默认选择REQUIRED-->
        <tx:method name="add" propagation="REQUIRED"/>
        <tx:method name="delete"/>
        <tx:method name="update"/>
        <!--read-only="true" 只读-->
        <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.bnzr.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
```

MyTest

import com.bnzr.mapper.UserMapper;
import com.bnzr.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class MyTest {
    @Test
    public void userTest(){
        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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值