文章目录

  • 前言
  • 1 Spring
  • 1.1 简介
  • 1.2 优点
  • 1.3 组成
  • 1.4 拓展
  • 2 IOC理论推导
  • 2.1 原代码方式
  • 2.1.1 实现方式
  • 2.1.2 弊端
  • 2.2 改进
  • 2.3 小结
  • 3 HelloSpring
  • 3.1 初识Spring
  • 4 IOC创建对象的方式
  • 4.1 使用无参构造创建对象(默认)
  • 4.2 使用有参构造创建对象:
  • 4.3 小结
  • 5 Spring配置
  • 5.1 别名
  • 5.2 Bean的配置
  • 5.3 import
  • 6 依赖注入
  • 6.1 构造器注入
  • 6.2 Set方式注入【重点】
  • 6.2.1 简介
  • 6.2.2 实例
  • 6.3 拓展方式注入
  • 6.3.1 c命名空间注入
  • 6.3.1.1 实现
  • 6.3.1.2 注意
  • 6.3.2 p命名空间注入
  • 6.3.2.1 实现
  • 6.3.2.2 注意
  • 6.4 bean的作用域
  • 6.4.1 单例模式(Spring默认机制)
  • 6.4.2 原型模式
  • 6.4.3 其他
  • 7 Bean的自动装配
  • 7.1 简介
  • 7.2 xml里autowire
  • 7.2.1 byName自动装配
  • 7.2.1.1 实现
  • 7.2.1.2 注意
  • 7.2.2 byType自动装配
  • 7.2.1.1 实现
  • 7.2.1.2 注意
  • 7.3 使用注解实现自动装配
  • 7.3.1 @Autowired
  • 7.3.1.1 在属性上使用
  • 7.3.1.2 在set方法上使用
  • 7.3.1.3 小结
  • 7.3.2 @Qualifier
  • 7.3.3 @Resource
  • 7.3.4 小结:
  • 8 使用注解开发
  • 8.1 过程
  • 8.1.1 导包
  • 8.1.2 配置
  • 8.1.3 属性如何注入
  • 8.2 衍生的注解
  • 8.3 自动装配
  • 8.4 作用域
  • 8.5 小结
  • 9 使用Java的方式配置Spring
  • 9.1 简介
  • 9.2 实现
  • 10 代理模式
  • 10.1 静态代理
  • 10.1.1 实现
  • 10.1.2 优缺点
  • 10.2 动态代理
  • 10.2.1 JDK动态代理实现
  • 10.2.2 JDK动态代理工具类
  • 11 AOP
  • 11.1 什么是AOP
  • 11.2 AOP在Spring中的作用
  • 11.3 使用Spring实现AOP
  • 11.3.1 使用Spring的API接口实现
  • 11.3.2 自定义类来实现AOP
  • 11.3.3 使用注解实现AOP
  • 12.1 步骤:
  • 12.2 回顾Mybatis
  • 12.3 Mybatis-Spring
  • 12.3.1 整合实现一
  • 12.3.2 整合一小结
  • 12.3.3 整合实现二



前言

文字部分参考【狂神说】Spring学习笔记(全),代码为自测代码。其中文字部分也加入了自己的理解。


1 Spring

1.1 简介

  • 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://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>

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

1.2 优点

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

1.3 组成

狂神说SpringBoot笔记md 狂神说java_AOP

1.4 拓展

  • 现代化的Java开发!说白就是基于Spring的开发!
  • Spring Boot
  • 一个快速开发的脚手架。
  • 基于SpringBoot可以快速的开发单个微服务。
  • 约定大于配置。
  • Spring Cloud
  • SpringCloud是基于SpringBoot实现的。
  • 因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
  • 弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”

2 IOC理论推导

2.1 原代码方式

2.1.1 实现方式

狂神说SpringBoot笔记md 狂神说java_AOP_02


UserDao 接口

package dao;

public interface UserDao {
    public void getUser();
}

UserDaoImpl 实现类

package dao;

public class UserDaoImpl implements UserDao{

    public void getUser() {
        System.out.println("默认实现");
    }
}
package dao;

public class UserDaoMysqlImpl implements UserDao{

    public void getUser() {
        System.out.println("mysql实现方式");
    }
}
package dao;

public class UserDaoOracleImpl implements UserDao{

    public void getUser() {
        System.out.println("Oracle实现方式");
    }
}

UserService 业务接口

package service;

public interface UserService {
    public void getUser();
}

UserServiceImpl 业务实现类

import dao.UserDao;
import dao.UserDaoImpl;
import dao.UserDaoMysqlImpl;
import dao.UserDaoOracleImpl;

public class UserServiceImpl implements UserService{

    public void getUser() {
        //UserDao userDao = new UserDaoImpl();
        //UserDao userDao = new UserDaoMysqlImpl();
        UserDao userDao = new UserDaoOracleImpl();
        userDao.getUser();
    }
}

测试

package service;

import org.junit.Test;

public class UserServiceTest {

    @Test
    public void userServiceTest(){
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }
}

2.1.2 弊端

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

2.2 改进

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

import dao.UserDao;

public class UserService2Impl implements UserService{
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void getUser() {
        userDao.getUser();
    }
}
  • 测试类:
@Test
    public void userService2Test(){
        UserService2Impl userService2 = new UserService2Impl();
        //userService2.setUserDao(new UserDaoImpl());
        //userService2.setUserDao(new UserDaoMysqlImpl());
        userService2.setUserDao(new UserDaoOracleImpl());
        userService2.getUser();
    }

2.3 小结

  • 之前,程序是主动创建对象!控制权在程序猿手上!
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!
  • 这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低~,可以更加专注的在业务的实现上!这是IOC的原型!
  • IOC本质
  • 控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
  • 采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
    控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

3 HelloSpring

3.1 初识Spring

  • 新建一个maven项目,结构如下:
  • 狂神说SpringBoot笔记md 狂神说java_spring_03

  • 编写dao接口和实现
package dao;

public interface Animal {
   public void say();
}
package dao;

import dao.Animal;

public class Cat implements Animal {
    public void say() {
        System.out.println("猫咪喵喵叫");
    }
}
package dao;

import dao.Animal;

public class Dog implements Animal {
    public void say() {
        System.out.println("狗砸汪汪叫");
    }
}
  • 编写service接口和实现
package service;

public interface Live {
    public void say();
}
package service;

import dao.Animal;

public class LiveImpl implements Live{
    private Animal animal;

    public void setAnimal(Animal animal) {
        this.animal = animal;
    }


    public void say() {
        animal.say();
    }
}
  • 配置bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="cat" class="dao.Cat"/>

    <bean id="dog" class="dao.Dog"/>

    <bean id="animalLive" class="service.LiveImpl">
        <property name="animal" ref="dog"/>
    </bean>

</beans>
  • 测试
package service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LiveImplTest {
    @Test
    public void liveTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        LiveImpl live = (LiveImpl) applicationContext.getBean("animalLive");
        live.say();
    }
}

4 IOC创建对象的方式

4.1 使用无参构造创建对象(默认)

4.2 使用有参构造创建对象:

  • 方式一:下标赋值
<bean id="user" class="dao.User">
        <constructor-arg index="0" value="1"></constructor-arg>
        <constructor-arg index="1" value="小明"></constructor-arg>
    </bean>
  • 类型(相同类型的参数按顺序赋值)
<bean id="user" class="dao.User">
        <constructor-arg type="int" value="1"></constructor-arg>
        <constructor-arg type="java.lang.String" value="小红"></constructor-arg>
    </bean>
  • 参数名
<bean id="user" class="dao.User">
        <constructor-arg name="id" value="1"></constructor-arg>
        <constructor-arg name="name" value="皮皮"></constructor-arg>
    </bean>

4.3 小结

  • 在配置文件加载的时候,容器中管理的对象就已经初始化了!
  • 在使用有参构造创建对象时,只需要构造方法,不需要set方法。

5 Spring配置

5.1 别名

<alias name="user" alias="old-user"/>
  • 在配置bean的xml文件中加入上述代码即可。
  • 上述代码的位置可以在被取别名的bean之前,也可在被取别名的bean之后
  • alias标签的name的值,可以是被取别名的bean的id值,也可以是被取别名的bean的name值。
  • 取了别名后,可以通过别名获取bean,也可以通过bean的id或name获取bean。

5.2 Bean的配置

<bean id="user" class="dao.User" name="o,p,q">
        <constructor-arg name="id" value="1"></constructor-arg>
        <constructor-arg name="name" value="皮皮"></constructor-arg>
    </bean>
  • id:bean的唯一标识符,也就是相当于我们学的对象名
  • class:bean对象所对应的全限定名:包名+类名
  • name:也是别名,而且name可以同时取多个别名

5.3 import

  • import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个。
  • 假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的。使用的时候,直接使用总的配置就可以了。
<import resource="beans.xml"/>

6 依赖注入

6.1 构造器注入

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

6.2 Set方式注入【重点】

6.2.1 简介

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

6.2.2 实例

  • 对象
package dao;

public class Address {
    private String address;

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

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

import java.util.*;

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

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

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

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

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

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

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

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

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}
  • 配置bean
<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="dao.Address">
        <property name="address" value="蓝星种花家"/>
    </bean>

    <bean id="student" class="dao.Student">
        <!--第一种:普通值注入,value        -->
        <property name="name" value="晒太阳的猫"/>
        <!--第二种:注入对象-->
        <property name="address" ref="address"/>
        <!--第三种:注入数组-->
        <property name="books">
            <array>
                <value>数学</value>
                <value>语文</value>
                <value>英语</value>
                <value>历史</value>
                <value>政治</value>
            </array>
        </property>
        <!--第三种:注入列表-->
        <property name="hobbies">
            <list>
                <value>小说</value>
                <value>音乐</value>
            </list>
        </property>
        <!--第四种:注入map-->
        <property name="card">
            <map>
                <entry key="银行卡" value="34321432143214213"/>
                <entry key="身份证" value="3213213213849384193249"/>
            </map>
        </property>
        <!--第五种:注入set-->
        <property name="games">
            <set>
                <value>荣耀</value>
                <value>吃鸡</value>
            </set>
        </property>
        <!--第六种:注入null-->
        <property name="wife">
            <null/>
        </property>
        <!--第六种:注入属性-->
        <property name="info">
            <props>
                <prop key="身高">163</prop>
                <prop key="体重">50</prop>
            </props>
        </property>
    </bean>
</beans>
  • 测试类
package dao;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StudentTest {

    @Test
    public void studentTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student);
    }
}

6.3 拓展方式注入

6.3.1 c命名空间注入

6.3.1.1 实现
  • pojo
package dao;

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

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
  • bean配置文件写法
  • 添加红框里的代码
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">
        
    <bean id="user" class="dao.User" c:id="1" c:name="花花"></bean>
</beans>
  • 测试类
package dao;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    @Test
    public void userTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
    }
}
6.3.1.2 注意
  • 使用c命名空间时,要在xml里加上xmlns:c="http://www.springframework.org/schema/c"说明
  • 如果配置bean时,没有用构造函数注入,那么pojo必须要有无参构造函数
  • 如果配置bean时,使用c命名空间注入全部的参数,那么pojo必须要有全参构造函数
  • 如果配置bean时,使用c命名空间注入部分的参数,那么pojo必须要有对应的部分参数的构造函数

6.3.2 p命名空间注入

6.3.2.1 实现
  • pojo
package dao;

public class Teacher {
    private int id;
    private String name;

    public void setId(int id) {
        this.id = id;
    }

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

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
  • bean配置文件写法
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="teacher" class="dao.Teacher" p:id="3" p:name="赵长远"></bean>
</beans>
  • 测试类
package dao;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TeacherTest {
    @Test
    public void userTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Teacher teacher = (Teacher) applicationContext.getBean("teacher");
        System.out.println(teacher);
    }
}
6.3.2.2 注意
  • 使用c命名空间时,要在xml里加上xmlns:p="http://www.springframework.org/schema/p"说明

6.4 bean的作用域

狂神说SpringBoot笔记md 狂神说java_AOP_04

6.4.1 单例模式(Spring默认机制)

<bean id="teacher" class="dao.Teacher" p:id="3" p:name="赵" scope="singleton"></bean>

或者

<bean id="teacher" class="dao.Teacher" p:id="3" p:name="赵"></bean>

6.4.2 原型模式

  • 每次从容器中get的时候,都会产生一个新对象!
<bean id="teacher" class="dao.Teacher" p:id="3" p:name="赵老师" scope="prototype"></bean>

6.4.3 其他

  • 其余的request、session、application、这些只能在web开发中使用到!

7 Bean的自动装配

7.1 简介

  • 自动装配是Spring满足bean依赖一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!
  • 在Spring中有三种装配的方式:
  • 在xml中显式的配置;
  • 在java中显式配置;
  • 隐式的自动装配bean【重要】

7.2 xml里autowire

  • 初始准备代码
package pojo;

public class Dog {
    private String name;

    public Dog(String name) {
        this.name = name;
    }

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

public class Cat {
    private String name="猫猫";

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

public class Person {
    private Dog dog;
    private Cat cat;

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

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

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

7.2.1 byName自动装配

7.2.1.1 实现
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <bean id="cat" class="pojo.Cat"/>

    <bean id="dog" class="pojo.Dog" c:name="狗大"/>
    
    <bean id="person" class="pojo.Person" autowire="byName"/>
</beans>
7.2.1.2 注意
  • byName的时候,需要保证所有bean的id唯一
  • 这个bean的id或者name的值要跟需要set的对象的属性名字一值。比如该例中Person有个属性是Dog dog,那么需要有个bean的id或者name为dog,才可以为person实现byName的自动装配。

7.2.2 byType自动装配

7.2.1.1 实现
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <bean id="cat" class="pojo.Cat"/>

    <bean id="dog1" class="pojo.Dog" c:name="狗二"/>
    
    <bean id="person" class="pojo.Person" autowire="byType"/>
</beans>
7.2.1.2 注意
  • byType的时候,需要保证所有bean的class唯一
  • 这个bean需要和自动注入的属性的类型一致!
  • 需要自动注入的属性必须有set方法。比如上例需要自动注入person的cat和dog属性,那么Person类必须有cat和dog的set方法。

7.3 使用注解实现自动装配

  • jdk1.5支持的注解,Spring2.5就支持注解了!
  • 要使用注解须知:
  • 导入约束
  • 配置注解的支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	        https://www.springframework.org/schema/beans/spring-beans.xsd
	        http://www.springframework.org/schema/context
	        https://www.springframework.org/schema/context/spring-context.xsd">
		
		<!--开启注解的支持    -->
        <context:annotation-config/>
</beans>

7.3.1 @Autowired

7.3.1.1 在属性上使用
  • 在属性上使用@Autowired,可以不写set方法。
package pojo;

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

public class Person {
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;

    @Override
    public String toString() {
        return "Person{" +
                "dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
7.3.1.2 在set方法上使用
package pojo;

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

public class Person {
    private Dog dog;
    private Cat cat;

    @Autowired
    public void setCat(Cat cat) {
        this.cat = cat;
    }
    
    @Autowired
    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
7.3.1.3 小结
  • 直接在属性上使用即可!也可以在set方法上使用!
  • 在属性使用Autowired我们就可以不用编写set方法了。
  • Autowired前提是你这个自动配置的属性在IOC(Spring)容器中存在,且类型唯一!

7.3.2 @Qualifier

  • 如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
  • 换个说法就是如果有两个bean都是同一类型,这时候光靠@Autowired就不够了,就需要加上@Qualifier(value = “xxx”)来确认是同类中的哪一个bean。
  • @Qualifier(value = “xxx”)必须依赖@Autowired,单独使用没有注入的效果。
<bean id="dog1" class="pojo.Dog"/>
    <bean id="dog2" class="pojo.Dog"/>
    <bean id="person" class="pojo.Person"/>
package pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
    private Dog dog;
    private Cat cat;

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

    @Autowired
    @Qualifier(value = "dog1")
    public void setDog(Dog dog) {
        this.dog = dog;
    }

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

7.3.3 @Resource

  • @Resource的作用类似@Autowired+@Qualifier(value = “xxx”)
<bean id="cat" class="pojo.Cat"/>
    <bean id="cat1" class="pojo.Cat"/>

    <bean id="dog1" class="pojo.Dog"/>
    <bean id="dog2" class="pojo.Dog"/>

    <bean id="person" class="pojo.Person"/>
package pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.annotation.Resource;

public class Person {
    private Dog dog;
    private Cat cat;

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

    @Autowired
    @Qualifier(value = "dog1")
    public void setDog(Dog dog) {
        this.dog = dog;
    }

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

7.3.4 小结:

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

8 使用注解开发

8.1 过程

8.1.1 导包

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

8.1.2 配置

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

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

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

8.1.3 属性如何注入

import org.springframework.stereotype.Component;

@Component
public class Cat {
    @Value("猫咪")
    private String name;

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

8.2 衍生的注解

  • @Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层。这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】

8.3 自动装配

见 7 Bean的自动装配

8.4 作用域

@Scope(“singleton”)

package pojo;

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

@Component
@Scope("singleton")
public class Cat {
    @Value("猫咪")
    private String name;

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

8.5 小结

  • xml与注解:
  • xml更加万能,适用于任何场合!维护简单方便
  • 注解不是自己类使用不了,维护相队复杂!
  • xml与注解最佳实践:
  • xml用来管理bean;
  • 注解只负责完成属性的注入;
  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持。

9 使用Java的方式配置Spring

9.1 简介

  • 我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
  • JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!
  • 这种纯Java的配置方式,在SpringBoot中随处可见!

9.2 实现

  • 实体类
  • 不需要加@Component
  • @Autowired还是需要的
package pojo;

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

public class Cat {
    @Value("猫咪")
    private String name;

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

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

public class Dog {
    @Value("狗砸")
    private String name;


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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class Person {
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;

    @Override
    public String toString() {
        return "Person{" +
                "dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
  • java配置文件
  • 配置文件名可以任意取
  • 类上要加@Configuration
  • 方法上要加@Bean
  • 方法名就是bean的名字
package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pojo.Cat;
import pojo.Dog;
import pojo.Person;

@Configuration
public class Myconfig {

    @Bean
    public Dog dog(){
        return new Dog();
    }

    @Bean
    public Cat cat(){
        return new Cat();
    }

    @Bean
    public Person getPerson(){
        return new Person();
    }
}
  • 测试类
package pojo;

import config.Myconfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
    @Test
    public void personTest(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Myconfig.class);
        Person person = (Person) applicationContext.getBean("getPerson");
        System.out.println(person);
    }
}

10 代理模式

  • 为什么要学习代理模式?因为这就是SpringAOP的底层!【SpringAOP和SpringMVC】
  • 代理模式的分类:
  • 静态代理
  • 动态代理

10.1 静态代理

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

10.1.1 实现

  • 接口
package pojo;

public interface Rent {
    public void rent();
}
  • 具体实现类
package pojo;

public class Host implements Rent{
    public void rent() {
        System.out.println("男房东出租房子");
    }
}
package pojo;

public class Hostress implements Rent{
    public void rent() {
        System.out.println("女房东出租房子");
    }
}
  • 代理类
package pojo;

public class Medium implements Rent{
    private Rent rent;
    public void rent() {
        see();
        rent.rent();
        fee();
    }

    public void setRent(Rent rent) {
        this.rent = rent;
    }

    public void see(){
        System.out.println("带看");
    }

    public void fee(){
        System.out.println("收费");
    }
}
  • 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
	        https://www.springframework.org/schema/beans/spring-beans.xsd
	        http://www.springframework.org/schema/context
	        https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="host" class="pojo.Host"/>

    <bean id="hostress" class="pojo.Hostress"/>

    <bean id="medium" class="pojo.Medium">
        <property name="rent" ref="hostress"/>
    </bean>
</beans>
  • 测试类
package pojo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Medium medium = (Medium) context.getBean("medium");
        medium.rent();
    }
}

10.1.2 优缺点

  • 代理模式的优点
  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共角色就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!
  • 代理模式的缺点:
  • 静态代理可以将接口的某一个方法增强,如果该接口有n个方法,都需要做同样的增强,就会产生很多重复工作。这时候我们迫切需要动态代理,以实现将某接口的所有方法做同样的增强。

10.2 动态代理

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

10.2.1 JDK动态代理实现

  • 被代理的接口
package pojo;

public interface Animal {
    public void say();

    public void eat();
}
  • 被代理的接口的一个实现类
package pojo;

public class Cat implements Animal{
    public void say() {
        System.out.println("猫子喵喵叫");
    }

    public void eat() {
        System.out.println("猫子爱吃肉");
    }
}
  • ProxyInvocationHandler类
package pojo;

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

public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Animal animal;

    //属性注入
    public void setAnimal(Animal animal) {
        this.animal = animal;
    }

    //获取代理对象,用以后面调用方法
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),animal.getClass().getInterfaces(),this);
    }

    //在代理对象调用方法时,通过反射调用方法。适用于该接口的所有方法。在这个方法里所作的增强动作将应用于该接口的所有方法。
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        logbefor(method.getName());
        Object invoke = method.invoke(animal, args);
        logafter(method.getName());
        return invoke;
    }

    public void logbefor(String str){
        System.out.println(str+"方法前的日志");
    }

    public void logafter(String str){
        System.out.println(str+"方法后的日志");
    }
}
  • 测试类
package pojo;

import org.junit.Test;

public class Mytest {
    
    @Test
    public void test(){
        Cat cat = new Cat();
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setAnimal(cat);
        Animal animal = (Animal) pih.getProxy();
        animal.say();
        animal.eat();

    }
}

10.2.2 JDK动态代理工具类

  • 动态代理工具类
package pojo;

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

public class ProxyInvocationHandlerUtil implements InvocationHandler {
    private Object object;

    public void setObject(Object object) {
        this.object = object;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), object.getClass().getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        fun1();
        Object invoke = method.invoke(object, args);
        fun2();
        return invoke;
    }

    public void fun1(){
        System.out.println("增强方法一");
    }

    public void fun2(){
        System.out.println("增强方法二");
    }
}
  • 测试
@Test
    public void test(){
        ProxyInvocationHandlerUtil pih = new ProxyInvocationHandlerUtil();
        pih.setObject(cat);
        Animal animal = (Animal) pih.getProxy();
        animal.say();
        animal.eat();
    }

11 AOP

11.1 什么是AOP

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

11.2 AOP在Spring中的作用

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

横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…

切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。

通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(Target):被通知对象。

代理(Proxy):向目标对象应用通知之后创建的对象。

切入点(PointCut):切面通知执行的“地点”的定义。

狂神说SpringBoot笔记md 狂神说java_AOP_05

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

狂神说SpringBoot笔记md 狂神说java_AOP_06


狂神说SpringBoot笔记md 狂神说java_AOP_07

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

11.3 使用Spring实现AOP

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

11.3.1 使用Spring的API接口实现

  • 1.导依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
  • 2.编写接口和实现类
package pojo;

public interface Animal {
    public void eat();

    public void drink();

    public void play();
}
package pojo;

public class AnimalCat implements Animal{
    public void eat() {
        System.out.println("猫咪吃东西");
    }

    public void drink() {
        System.out.println("猫咪喝水水");
    }

    public void play() {
        System.out.println("猫咪玩耍");
    }
}
package pojo;

public class AnimalDog implements Animal{
    public void eat() {
        System.out.println("狗狗吃东西");
    }

    public void drink() {
        System.out.println("狗狗喝水水");
    }

    public void play() {
        System.out.println("狗狗玩耍");
    }
}
  • 3.编写aop增强类
package log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class BeforeLog implements MethodBeforeAdvice {

    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("前置日志"+target.getClass().getName()+"类的"+method.getName()+"方法");
    }
}
package log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置日志"+target.getClass().getName()+"类的"+method.getName()+"方法");
        System.out.println("=================================================");
    }
}
  • 4.去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束,配置bean的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	        https://www.springframework.org/schema/beans/spring-beans.xsd
	        http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">

        <bean id="cat" class="pojo.AnimalCat"/>

        <bean id="dog" class="pojo.AnimalDog"/>

        <bean id="before" class="log.BeforeLog"/>

        <bean id="after" class="log.AfterLog"/>

        <aop:config>
            <!--切入点:expression:表达式,execution(要执行的位置!* * * * *)-->
            <aop:pointcut id="addlog" expression="execution(* pojo.Animal*.*(..))"/>
            <!--在切入点加上before通知-->
            <aop:advisor advice-ref="before" pointcut-ref="addlog"/>
            <!--在切入点加上after通知-->
            <aop:advisor advice-ref="after" pointcut-ref="addlog"/>
        </aop:config>

</beans>
  • 5.测试
package pojo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

       Animal cat = (Animal) context.getBean("cat");
        cat.eat();
        cat.drink();
        cat.play();
        Animal dog = (Animal) context.getBean("dog");
        dog.eat();
        dog.drink();
        dog.play();
    }
}

11.3.2 自定义类来实现AOP

  • 1.导依赖包
  • 2.编写接口和实现类
  • 3.编写自定义增强类
package log;

public class DiyLog {
    public void before(){
        System.out.println("前日志");
    }

    public void after(){
        System.out.println("后日志");
    }
}
  • 4.去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束,配置bean的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	        https://www.springframework.org/schema/beans/spring-beans.xsd
	        http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="cat" class="pojo.AnimalCat"/>

    <bean id="dog" class="pojo.AnimalDog"/>

    <bean id="diylog" class="log.DiyLog"/>

    <aop:config>
        <!--切入点:expression:表达式,execution(要执行的位置!* * * * *)-->
        <aop:pointcut id="addlog" expression="execution(* pojo.Animal*.*(..))"/>
        <aop:aspect ref="diylog">
            <aop:before method="before" pointcut-ref="addlog"/>
            <aop:after method="after" pointcut-ref="addlog"/>
        </aop:aspect>
    </aop:config>
    
</beans>
  • 5.测试
@Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");

        Animal cat = (Animal) context.getBean("cat");
        cat.eat();
        cat.drink();
        cat.play();
        Animal dog = (Animal) context.getBean("dog");
        dog.eat();
        dog.drink();
        dog.play();
    }

11.3.3 使用注解实现AOP

  • 1.导依赖包
  • 2.编写接口和实现类
  • 3.定义注解实现的AnnotationPointCut增强类
package log;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Bean;

//声明式事务!
@Aspect //标注这个类是一个切面
public class AnnotationLog {
    @Before("execution(* pojo.Animal*.*(..))")
    public void before(){
        System.out.println("前日志");
    }
    @After("execution(* pojo.Animal*.*(..))")
    public void after(){
        System.out.println("后日志");
    }
}
  • 4.在Spring配置文件中,注册bean,并增加支持注解的配置。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	        https://www.springframework.org/schema/beans/spring-beans.xsd
	        http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="cat" class="pojo.AnimalCat"/>

    <bean id="dog" class="pojo.AnimalDog"/>

    <bean id="annotation" class="log.AnnotationLog"/>

    <!--开启注解支持! JDK(默认是 proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy/>
    
</beans>
  • 5.测试
@Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");

        Animal cat = (Animal) context.getBean("cat");
        cat.eat();
        cat.drink();
        cat.play();
        Animal dog = (Animal) context.getBean("dog");
        dog.eat();
        dog.drink();
        dog.play();
    }

12.1 步骤:

  • 1.导入相关jar包
  • junit
  • mybatis
  • mysql数据库
  • spring相关
  • aop织入器
  • mybatis-spring整合包【重点】在此还导入了lombok包。
  • 配置Maven静态资源过滤问题!
<dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>

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

        <!--Spring操作数据库的话,还需要一个spring-jdbc
               -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.4</version>
        </dependency>

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

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

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
  • 2.编写配置文件
  • 3.测试

12.2 回顾Mybatis

编写pojo实体类
编写实现mybatis的配置文件
编写UserMapper接口
编写UserMapper.xml文件
测试

12.3 Mybatis-Spring

  • 什么是MyBatis-Spring?
  • MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
  • 文档链接:http://mybatis.org/spring/zh/index.html
  • 如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:
<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

12.3.1 整合实现一

  • 引入Spring配置文件spring-mybatis.xml(名字自取)
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
  • 配置数据源替换mybaits的数据源。这里数据源的具体信息还是从属性文件读取的,要加红框里的信息。测试时遇到用户名属性文件配置成username并读取username就连不上数据库,改成别的就可以。最后改成user做了连接。
  • 配置SqlSessionFactory,关联MyBatis
  • 注册sqlSessionTemplate,关联sqlSessionFactory
  • 需要UserMapper接口的UserMapperImpl 实现类,私有化sqlSessionTemplate
package dao;

import org.mybatis.spring.SqlSessionTemplate;
import pojo.User;

public class UserMapperImpl implements UserMapper{
    //我们的所有操作,都使用sqlSession来执行,在原来,现在都使用SqlsessionTemplate
    private SqlSessionTemplate sqlSession;

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

    public User getUserById(int id) {

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUserById(id);
    }
}
  • 将自己写的实现类,注入到Spring配置文件中。
  • 整个spring-mybatis.xml代码如下
<?xml version="1.0" encoding="GBK"?>
<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:property-placeholder location="classpath:db.properties"/>
    <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
我们这里使用Spring提供的JDBC:-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>

    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--关联mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>

    </bean>

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

    <bean id="userMapper" class="dao.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>
  • 测试
@Test
    public void test ()  {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");

        UserMapper userMapper = (UserMapper) context.getBean("userMapper");
        System.out.println(userMapper.getUserById(1));
    }

12.3.2 整合一小结

  • 整合一的关键是spring-mybatis.xml文件(这个文件名自己取,只要和测试时的ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");文件名匹配上就可以了)。
  • spring-mybatis.xml文件里配置了数据源
    所以原mybatis的核心配置文件里的environments就可以去掉。
  • spring-mybatis.xml文件里配置了sqlSessionFactory,用的是spring提供的SqlSessionFactoryBean。

    所以原mybatis的获取SqlSession的类可以去掉。
  • 建议Mappe.xml的配置还是放在mybatis核心 配置文件中

    不要配在下图红框下面,测试时试过<property name="mapperLocations" value="classpath:dao/*.xml"/>通配写法报找不到文件<property name="mapperLocations" value="classpath:dao/UserMapper.xml"/>就可以。

12.3.3 整合实现二

  • mybatis-spring1.2.3版以上的才有这个,官方文档截图:
  • dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起整合方式一 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看。
  • 将我们上面写的UserMapperImpl修改成UserMapperImpl1,重点是继承SqlSessionDaoSupport:
package dao;

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

public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper{
    public User getUserById(int id) {
        return getSqlSession().getMapper(UserMapper.class).getUserById(1);
    }
}
  • SqlSessionDaoSupport类有个sqlSessionFactory属性要在配置bean的时候注入。
<bean id="userMapper1" class="dao.UserMapperImpl1">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  • 测试
@Test
    public void test3 ()  {

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

        UserMapper userMapper1 = (UserMapper) context.getBean("userMapper1");
        System.out.println(userMapper1.getUserById(1));
    }