Spring笔记

Spring

1、概述

1.1、简介

  • Spring:春天 ---> 给软件行业带来了春天
  • 2002年,Rod Jahnson首次推出了Spring框架维形interface21框架。
  • 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
  • 很难想象Rod Johnson(Spring Frameword的创始人)的学历,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
  • Spring理念:使现有技术更加实用,本身就是一个大杂绘,整合现有的框架技术

SSH:Struct2 + Spring + Hibernate

SSM:SpringMvc + Spring + Mybatis

1.2、相关地址及依赖

相关地址:

依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.21</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.21</version>
</dependency>

1.3、优点

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

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

1.4、组成

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

image-20220716171519172

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

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

1.5、扩展

SpringBoot与SpringCloud

  • SpringBoot 是 Spring 的一套快速配置脚手架,可以基于SpringBoot 快速开发单个微服务;
  • SpringCloud是基于SpringBoot实现的;
  • SpringBoot专注于快速、方便集成的单个微服务个体,SpringCloud关注全局的服务治理框架;
  • SpringBoot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 ,SpringCloud很大的一部分是基于SpringBoot来实现,SpringBoot可以离开SpringCloud独立使用开发项目,但是SpringCloud离不开SpringBoot,属于依赖的关系。
  • SpringBoot在SpringCloud中起到了承上启下的作用,如果你要学习SpringCloud必须要学习 SpringBoot。
  • 现在很多公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要掌握Spring及SpringMvc!

弊端:发展太久之后,违背了原来的里面,现在配置十分繁琐,人称:”配置地狱“,所以推出了SpringBoot。

2、IOC理论推导

2.1、创建环境进行测试

新建一个空白的maven项目

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

1、先写一个UserDao接口

public interface UserDao {
    void getUser();
}

2、再去写Dao的实现类

public class UserDaoImpl implements UserDao {
    public void getUser() {
        System.out.println("获取用户信息");
    }
}

3、然后去写UserService的接口

public interface UserService {
	public void getUser();
}

4、最后写Service的实现类

public class UserServiceImpl implements UserService {
	private UserDao userDao = new UserDaoImpl();
    public void getUser() {
        userDao.getUser();
    }
}

5、测试一下

@Test
public void test(){
    UserService service = new UserServiceImpl();
    service.getUser();
}

这是我们原来的方式,开始也都是这么去写的,我们现在修改一下。

把Userdao的实现类增加一个

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

紧接着我们要去使用MySql的话 , 我们就需要去service实现类里面修改对应的实现

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoMySqlImpl();
    public void getUser() {
        userDao.getUser();
    }
}

再假设, 我们再增加一个Userdao的实现类

public class UserDaoOracleImpl implements UserDao {
    public void getUser() {
        System.out.println("Oracle数据库获取用户信息");
    }
}

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

那我们如何去解决呢 ?

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

public class UserServiceImpl implements UserService {
    private UserDao userDao;

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

    public void GetUser() {
        userDao.getUser();
    }
}

现在去我们的测试类里 , 进行测试

@Test
public void test(){
    UserServiceImpl service = new UserServiceImpl();
    service.setUserDao( new UserDaoMySqlImpl() );
    service.getUser();
    //那我们现在又想用Oracle去实现呢
    service.setUserDao( new UserDaoOracleImpl() );
    service.getUser();
}

这两种办法发现了区别没有,可能很多人说没啥区别,但其实他们已经发生了根本性的变化。

以前所有东西都是由程序去进行控制创建,而现在是由我们自行控制创建对象,把主动权交给了调用者。程序不用去管怎么创建,怎么实现了,它只负责提供一个接口。

这种思想,从本质上解决了问题,我们程序员不再去管理对象的创建了,更多的时间去关注业务的实现。耦合性大大降低,这也就是IOC的原型 !

2.2、IOC的本质

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

image-20220716183144032

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

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

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

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


3、HelloWord

3.1、导入相关依赖

注 : spring 需要导入commons-logging进行日志记录,我们使用maven进行相关依赖的下载(webmvc包含大部分spring需要用到的依赖)

<!--spring核心依赖库-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.21</version>
</dependency>

3.2、编写代码

  1. 编写Hello实体类

    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 + '\'' +
                    '}';
        }
    }
    
  2. 编写spring文件,命名为beans.xml,便于理解,原名为application.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!--
        使用Spring来创建对象,在Spring这些都称为Bean
        id:变量名
        class:new的对象
        property:给对象中的属性设置一个值
    -->
        <bean id="hello" class="com.yzh.pojo.Hello">
            <property name="str" value="SpringBeans" />
        </bean>
        
    </beans>
    
    
  3. 编写测试类

    public class MyTest {
        public static void main(String[] args) {
            //获取Spring的上下文对象
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            //注册到Spring容器中的对象,需要使用的话直接从里面取出来即可
            //getBean:参数即为spring配置文件中bean的id
            Hello hello = (Hello) context.getBean("hello");
    
            System.out.println(hello.toString()); //输出:Hello{str='SpringBeans'}
        }
    }
    

3.3、思考

  • Hello对象是谁创建的?【hello对象是由Spring创建的】
  • Hello对象的属性是怎么设置的?【hello对象的属性是由Spring容器设置的】

这个过程就叫控制反转:

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

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

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

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

3.4、修改案例1

在案例1中,新增Spring配置文件beans.xml

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

    <bean id="Impl" class="com.yzh.dao.UserDaoImpl" />
    <bean id="mysqlImpl" class="com.yzh.dao.UserDaoMysqlImpl" />
    <bean id="orcleImpl" class="com.yzh.dao.UserDaoOracleImpl" />

    <bean id="UserServiceImpl" class="com.yzh.service.UserServiceImpl" >
        <!--
            引用另外一个bean , 不是用value 而是用 ref
            ref:引用Spring容器中创建好的对象
            value:具体的值,基本数据类型
        -->
        <property name="userDao" ref="mysqlImpl" />
        <!--注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写-->
    </bean>
    
</beans>

测试

@Test
public void SpringTest(){
    //获取ApplicationContext:拿到Spring的容器
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
    userServiceImpl.getUser();
}

现在修改实现方式不用再去程序中进行修改了,要实现不同的方式,只需要在xml配置文件中进行修改,所谓的Ioc,就是:对象由Spring来创建,管理,装配。


4、IOC创建对象的方式

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

    public class User {
        private String name;
    
        public User() {
            System.out.println("User实体类无参方法");
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void show(){
            System.out.println("name = " + name);
        }
    }
    
    
    <bean id="user" class="com.yzh.pojo.User">
        <property name="name" value="小明" />
    </bean>
    
    @Test
    public void testSpring03(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //在执行getBean之前, user已经创建好了 , 通过无参构造
        User user = (User) context.getBean("user");
        user.show();
    }
    

    在执行getBean之前, user已经创建好了 , 通过无参构造

  2. 假设需要使用有参构造创建对象。

    1. 下标赋值

      <!--第一种,下标赋值-->
      <bean id="user" class="com.yzh.pojo.User">
          <constructor-arg index="0" value="小明" />
      </bean>
      
    2. 类型

      <!--
      	第二种,通过类型创建,不推荐使用
      	(基本类型直接用,String等包装类型需要带包名)
      -->
      <bean id="user" class="com.yzh.pojo.User">
          <constructor-arg type="java.lang.String" value="小明" />
      </bean>
      
    3. 参数名

      <!--第三种,直接通过参数名来设置-->
      <bean id="user" class="com.yzh.pojo.User">
      	<constructor-arg name="name" value="小明" />
      </bean>
      

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


5、Spring配置

5.1、别名

  • alias 设置别名 , 为bean设置别名 , 可以设置多个别名
<!--如果添加了别名,可以使用别名获取到这个对象-->
<alias name="user" alias="userNew" />

5.2、Bean的配置

  • bean就是java对象,由Spring创建和管理

  • id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符

  • name可以设置多个别名,可以用逗号,分号,空格隔开

  • 如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;

  • class是bean的全限定名=包名+类名

<!--bean就是java对象,由Spring创建和管理-->
<!--
    id;bean的唯一标识符,可以理解为对象名
    class:bean对象所对应的全限定名:包名 + 类名
    name:也是别名,而且可以同时取多个别名,可以使用多种符号分割
-->
<bean id="userT" class="com.yzh.pojo.UserT" name="user2 u2,u3;u4">
    <property name="name" value="小明" />
</bean>

5.3、import

团队的合作通过import来实现 ,一般最后使用applicationContext.xml作为主配置文件.

<!-- 
	例如:<import resource="{path}/beans.xml"/>
-->
<import resource="beans.xml" />
<import resource="beans2.xml" />
<import resource="beans3.xml" />

6、依赖注入(DI)

  • 依赖注入(Dependency Injection,DI)。
  • 依赖:指Bean对象的创建依赖于容器,Bean对象的依赖资源。
  • 注入:指Bean对象所依赖的资源,由容器来设置和装配。

6.1、构造器注入

前面的constructor注入方式就是构造器注入,例如:

<bean id="user" class="com.yzh.pojo.User">
	<constructor-arg name="name" value="小明" />
</bean>

6.2、Set方式注入【重点】

依赖注入:Set注入!

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

6.2.1、环境搭建

1、复杂类型

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

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

2、真实测试对象

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
    
    //对应的get,set,toString方法
}

3、beans.xml【重点:多种方式注入值】

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

        <bean id="address" class="com.yzh.pojo.Address">
            <property name="address" value="重庆" />
        </bean>

        <bean id="student" class="com.yzh.pojo.Student">
            <!--普通值注入,value-->
            <property name="name" value="小明" />
            <!--Bean注入,ref-->
            <property name="address" ref="address" />
            <!--数组-->
            <property name="books">
                <array>
                    <value>三国演义</value>
                    <value>水浒传</value>
                    <value>西游记</value>
                    <value>红楼梦</value>
                </array>
            </property>
            <!--List集合-->
            <property name="hobbys">
                <list>
                    <value>看直播</value>
                    <value>敲代码</value>
                    <value>看电影</value>
                </list>
            </property>
            <!--Map集合-->
            <property name="card">
                <map>
                    <entry key="身份证" value="510521" />
                    <entry key="电话号码" value="1511111" />
                </map>
            </property>
            <!--Set集合-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>CF</value>
                    <value>DNF</value>
                </set>
            </property>
            <!--空类型-->
            <property name="wife">
                <null/>
            </property>
            <!--Properties集合-->
            <property name="info">
                <props>
                    <prop key="学号">1001</prop>
                    <prop key="年龄">20</prop>
                    <prop key="性别">男</prop>
                </props>
            </property>
        </bean>
</beans>

4、测试类

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

6.2.2、常用注入方式

1、普通值注入

<!--普通值注入,value-->
<property name="name" value="小明" />

2、Bean注入,这里的值是一个引用,ref

<bean id="address" class="com.yzh.pojo.Address">
    <property name="address" value="重庆" />
</bean>

<bean id="student" class="com.yzh.pojo.Student">
    <!--Bean注入,ref-->
    <property name="address" ref="address" />
</bean>

3、数组注入

<property name="books">
    <array>
        <value>三国演义</value>
        <value>水浒传</value>
        <value>西游记</value>
        <value>红楼梦</value>
    </array>
</property>

4、List注入

<!--List集合-->
<property name="hobbys">
    <list>
        <value>看直播</value>
        <value>敲代码</value>
        <value>看电影</value>
    </list>
</property>

5、Map注入

<!--Map集合-->
<property name="card">
    <map>
        <entry key="身份证" value="510521" />
        <entry key="电话号码" value="1511111" />
    </map>
</property>

6、Set注入

<!--Set集合-->
<property name="games">
    <set>
        <value>LOL</value>
        <value>CF</value>
        <value>DNF</value>
    </set>
</property>

7、Null注入

 <!--空类型Null-->
<property name="wife">
    <null/>
</property>

8、Properties注入

<!--Properties集合-->
<property name="info">
    <props>
        <prop key="学号">1001</prop>
        <prop key="年龄">20</prop>
        <prop key="性别">男</prop>
    </props>
</property>

6.3、扩展方式注入

我们可以使用p命名空间和c命名空间进行注入

<!--c命名空间注入,需要无参构造器,可以直接注入属性的值,property-->
<bean id="user" class="com.yzh.pojo.User" p:age="18" p:name="小明"/>

<!--c命名空间注入,需要有参构造器,通过构造器注入,construct-args-->
<bean id="user2" class="com.yzh.pojo.User" c:age="20" c:name="小红" />

c命名空间需要有参构造器,否则会爆红

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

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

7、Bean

7.1、Bean作用域

image-20220724143113630

image-20220724151510329

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

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

2、原型模式:每次从容器中获取的时候,都会产生一个新对象

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

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

7.2、Bean的自动装配

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

在Spring中自动装配的三种方式:

  1. 在xml中显示的装配
  2. 在java中显示装配
  3. 隐式的自动装配和bean【重要】

推荐不使用自动装配xml配置,而使用注解。

7.3、测试环境

测试环境:一个人有两只宠物,一只猫,一只狗

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

<bean id="peopel" class="com.yzh.pojo.Peopel">
    <property name="name" value="小明"/>
    <property name="cat" ref="cat"/>
    <property name="dog" ref="dog" />
</bean>

测试:

@Test
public void testSpring05(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Peopel peopel = context.getBean("peopel", Peopel.class);
    peopel.getCat().shout();
    peopel.getDog().shout();
}

7.4、byName自动装配

按名称自动装配

byName:会自动在上下文中寻找,和自己对象set方法后面的值对应的beanid

<bean id="peopel" class="com.yzh.pojo.Peopel" autowire="byName">
    <property name="name" value="小明"/>
</bean>

7.5、byType自动装配

按类型自动装配

byType:会自动在上下文中寻找,和自己属性类型相同的bean(可以不需要id,但是只能存在一个类型的bean)

<bean id="peopel" class="com.yzh.pojo.Peopel" autowire="byType">
    <property name="name" value="小明"/>
</bean>

byName,byType小结

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

7.6、使用注解实现自动装配【重点】

jdk1.5开始支持注解,spring2.5开始全面支持注解。

  1. 在spring配置文件中引入context文件头(约束)
  2. 开启属性注解支持! <context:annotation-config/>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

@Autowired

@Autowired(required = false)
@Qualifier(value = "dog22")
private Dog dog;
  • 直接在属性上使用即可,也可以在set方法上使用!

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

  • 如果显示的定义了@Autowired的required属性为false,就说明这个对象可以为null,否则不允许为空。

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

@Qualifier

  • @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配

  • @Qualifier不能单独使用。

@Nullable

  • 字段标记了该属性,说明这个字段可以为Null

@Resource

  • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  • 其次再进行默认的byName方式进行装配;
  • 如果以上都不成功,则按byType的方式自动装配。
@Resource(name = "cat11")
private Cat cat;

小结:

@Autowired 和 @Resource 的区别:

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

  • @Autowired通过byType的方式实现,而且必须要求这个对象存在,如果有多个类型需要的话,需要配合@Qualifier(value = "xxx")使用【常用】

  • @Resouces默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!如果有多个类型需要的话,需要配合name属性指定【常用】

  • 执行顺序不同:@Autowired通过byType的方式实现,@Resouces默认通过byname的方式实现


8、使用注解开发

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

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

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

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

</beans>
  1. bean

  2. 属性如何注入【@Value可以放在属性上,也可以放在set方法上】

    @Component
    public class User {
        @Value("小明")
        public String name;
    
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 衍生的注解

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

    • dao 【@Repository】

    • service [@Service]

    • controller [@clontroller]

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

  4. 自动装配

    @scope

    • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
    • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收。
    - @Autowired:自动装配通过类型,名字
    	如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
    - @nullable 字段标记了这个注解,说明这个字段可以为nu11;
    - @Resource :自动装配通过名字,类型。
    
  5. 作用域

    @Scope("singleton") //单例
    @Scope("prototype") //原型
    public class User {}
    
  6. 小结

    XML与注解比较

    • XML可以适用任何场景 ,结构清晰,维护方便
    • 注解不是自己提供的类使用不了,开发简单方便

    xml与注解整合开发 :推荐最佳实践

    • xml管理Bean
    • 注解完成属性注入
    • 使用过程中, 可以不用扫描,扫描是为了类上的注解 <context:annotation-config/>

    作用:

    • 进行注解驱动注册,从而使注解生效
    • 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
    • 如果不扫描包,就需要手动配置bean
    • 如果不加注解驱动,则注入的值为null!

9、使用Java的方式来配置Spring

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

实体类

//注册为一个组件,被Spring容器托管
@Component
public class User {

    //属性注入,也可以写在set方法上
    @Value("小明")
    private String name;

    public String getName() {
        return name;
    }

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

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

配置类

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

//这个也会被Spring容器托管,注册到容器中,因为它本身也是一个组件@Component
//@Configuration代表这是一个配置类,和beans.xml一样
@Configuration
@ComponentScan("com.yzh.pojo")
@Import(SpringConfig2.class) //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class SpringConfig {

    //这是一个bean,相当于xml文件中的bean标签
    //方法的名字就相当于bean中的id属性
    //方法的返回值就相当于bean中的class属性
    @Bean
    public User getUser(){
        return new User(); //返回注入到bean的对象
    }
}

测试类

@Test
public void testSpring07(){
    //如果完全使用配置的方式,就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
    ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
    User user = context.getBean("getUser", User.class);
    System.out.println(user.toString());
}

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


10、代理模式

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

代理模式的分类:

  • 静态代理
  • 动态代理

image-20220724210949647

10.1、静态代理

静态代理角色分析

  • 抽象角色:一般使用接口或者抽象类来实现
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色;代理真实角色,一般会做一些附属的操作。
  • 客户:使用代理角色来进行一些操作。

代码步骤:

  1. 接口

    //租房接口
    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

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

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

    public class Client {
        public static void main(String[] args) {
            Landlord landlord = new Landlord();
            Proxy proxy = new Proxy(landlord);
            proxy.rent();
        }
    }
    

代理模式的好处

  • 可以使得我们的真实角色更加纯粹。
  • 不再去关注一些公共的事情,公共的业务由代理来完成。
  • 实现了业务的分工,公共业务发生扩展时变得更加集中和方便。

缺点

类多了,多了代理类,工作量变大了,开发效率降低。(一个真实角色会产生一个代理角色,代理量翻倍)

我们想要静态代理的好处,又不想要静态代理的缺点,所以,就有了动态代理!

10.2、加深静态代理理解

创建一个抽象角色,比如咋们平时做的用户业务,抽象起来就是增删改查!

在已经完成业务代码的时候新需求来了,需要增加一个日志功能,怎么实现!

  • 思路1 :在实现类上增加代码 【麻烦!】
  • 思路2:使用代理来做,能够不改变原来的业务情况下,实现此功能就是最好的了!
  1. 接口

    //接口
    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void query();
    }
    
  2. 真实角色

    //真实对象,完成增删改查操作的人
    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        public void update() {
            System.out.println("修改了一个用户");
        }
    
        public void query() {
            System.out.println("查询了一个用户");
        }
    }
    
  3. 代理角色

    //代理角色,这里实现新增日志功能
    public class UserServiceProxy implements UserService {
        private UserServiceImpl userService;
    
        public void setUserService(UserServiceImpl userService) {
            this.userService = userService;
        }
    
    
        public void add() {
            log("add");
            userService.add();
        }
    
        public void delete() {
            log("delete");
            userService.delete();
        }
    
        public void update() {
            log("update");
            userService.update();
        }
    
        public void query() {
            log("query");
            userService.query();
        }
    
        public void log(String msg){
            System.out.println("[Debug] 执行了" + msg + "方法");
        }
    }
    
  4. 客户端访问代理

    //测试访问类
    public class Client {
        public static void main(String[] args) {
            UserServiceImpl userService = new UserServiceImpl();
            UserServiceProxy proxy = new UserServiceProxy();
            proxy.setUserService(userService);
            proxy.query();
        }
    }
    

我们在不改变原来的代码的情况下,实现了对原有功能的增强,这是AOP中最核心的思想

【聊聊AOP:纵向开发,横向开发】

image-20220724215957381

10.3、动态代理

  • 动态代理的角色和静态代理的一样 .
  • 动态代理的代理类是动态生成的,静态代理的代理类是我们提前写好的
  • 动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理
    • 基于接口的动态代理----JDK动态代理
    • 基于类的动态代理--cglib
    • 现在用的比较多的是 javasist (java字节码)来生成动态代理 . 百度一下javasist
    • 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!

JDK的动态代理需要了解两个类

核心 : InvocationHandler 和 Proxy , 查询JDK帮助文档查看相关内容

【InvocationHandler:调用处理程序】【Proxy :代理】

Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。 方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。 原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean
//生成代理类
public Object getProxy(){
        return Proxy.newProxyInstance(
            this.getClass().getClassLoader(), 
            rent.getClass().getInterfaces(), 
            this);
    }

代码过程:

  1. 接口

    //租房接口
    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

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

    public class ProxyInvocationHandle implements InvocationHandler {
    
        private Rent rent;
    
        public void setRent(Rent rent) {
            this.rent = rent;
        }
    
        //生成得到代理类
        public Object getProxy(){
            return Proxy.newProxyInstance(
                    this.getClass().getClassLoader(),
                    rent.getClass().getInterfaces(),
                    this);
        }
    
        //处理代理实例,并返回结果
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //动态代理的本质,就是通过反射机制实现!
            seeHouse();
            Object result = method.invoke(rent, args);
            fare();
            return result;
        }
    
        public void seeHouse(){
            System.out.println("中介带看房子");
        }
    
        public void fare(){
            System.out.println("收中介费");
        }
    }
    
  4. 访问代理

    public class Client {
        public static void main(String[] args) {
            //真实角色
            Landlord landlord = new Landlord();
            //代理角色,现在没有
            ProxyInvocationHandle pih = new ProxyInvocationHandle();
            pih.setRent(landlord);
            Rent proxy = (Rent) pih.getProxy(); //这里的proxy就是动态生成的,我们并没有写
            proxy.rent();
        }
    }
    

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

10.4、加深动态代理理解

我们来使用动态代理实现代理我们后面写的UserService!

我们也可以编写一个通用的动态代理实现的类!所有的代理对象设置为Object即可!

动态代理类:

public class ProxyInvocationHandle implements InvocationHandler {

    private Object target;

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

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

    //处理代理实例,并返回结果
    //proxy : 代理类
    //method : 代理类的调用处理程序的方法对象
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

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

测试类:

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

        //代理对象,不存在
        ProxyInvocationHandle pih = new ProxyInvocationHandle();
        pih.setTarget(userService);//设置要代理的对象
        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();
        proxy.delete();
    }
}

10.5、动态代理的好处

静态代理有的它都有,静态代理没有的,它也有!

  • 可以使得我们的真实角色更加纯粹,不再去关注一些公共的事情。
  • 公共的业务由代理来完成,实现了业务的分工。
  • 公共业务发生扩展时变得更加集中和方便。
  • 一个动态代理,一般代理某一类业务。
  • 一个动态代理可以代理多个类,代理的是接口!

11、AOP

11.1、什么是AOP

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

image-20220724230810393

11.2、Aop在Spring中的作用

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

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

image-20220725102145379

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

image-20220724231142544

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

10.3、使用Spring实现Aop【重点:3种方式】

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

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

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

  1. 接口

    //接口
    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void query();
    }
    
  2. 真实对象

    //真实对象,完成增删改查操作的人
    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        public void update() {
            System.out.println("修改了一个用户");
        }
    
        public void query() {
            System.out.println("查询了一个用户");
        }
    }
    
  3. 前置日志和后值日志

    import org.springframework.aop.MethodBeforeAdvice;
    
    import java.lang.reflect.Method;
    
    public class Log implements MethodBeforeAdvice {
    
        //method:要执行的目标对象的方法
        //args:参数
        //target:目标对象
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println(target.getClass().getName() + "的" + method.getName() + "被执行了");
        }
    }
    
    import org.springframework.aop.AfterReturningAdvice;
    
    import java.lang.reflect.Method;
    
    public class AfterLog implements AfterReturningAdvice {
    
        //returnValue:返回值
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
        }
    }
    
  4. 配置文件applicationContext.xml【需要导入aop依赖及约束】

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--注册bean-->
        <bean id="log" class="com.yzh.log.Log" />
        <bean id="afterLog" class="com.yzh.log.AfterLog" />
        <bean id="userService" class="com.yzh.service.UserServiceImpl" />
    
        <!--方式一:使用原生的Spring API方法-->
        <!--配置aop:需要导入aop的约束-->
        <aop:config>
            <!--切入点:expression:表达式,execution(要执行的位置!* * * * *)-->
            <aop:pointcut id="pointcut" expression="execution(* com.yzh.service.UserServiceImpl.*(..))"/>
    
            <!--执行环绕增加-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut" />
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" />
        </aop:config>
    
    </beans>
    
  5. 测试类

    @Test
        public void testSpring09(){
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = context.getBean("userService", UserService.class);
            userService.add();
        }
    
  6. 输出

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

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

//自定义切面类
public class DiyPointCut {
    public void before(){
        System.out.println("===方式执行前===");
    }
    public void after(){
        System.out.println("===方式执行后===");
    }
}

applicationContext.xml

<!--方式二:自定义类-->
<bean id="diy" class="com.yzh.diy.DiyPointCut"/>

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

</aop:config>

测试类和第一种方式一样。

方式三:使用注解实现!

//使用注解方式实现Aop
@Component //标注为一个bean组件,注册
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.yzh.service..*.*(..))")
    public void before(){
        System.out.println("====方式执行前====");
    }

    @After("execution(* com.yzh.service..*.*(..))")
    public void after(){
        System.out.println("====方式执行后====");
    }
    
    @Around("execution(* com.yzh.service..*.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        //获得签名 相当于返回值 + 方法路径 + 方法名
        Signature signature = jp.getSignature();
        System.out.println("signature:" + signature);
        Object proceed = jp.proceed();
        System.out.println("环绕后");
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    
	<!--方式三:使用注解-->
    <!--开启注解扫描-->
    <context:component-scan base-package="com.yzh.diy" />
    <!--开启注解-->
    <context:annotation-config />
    <!--
        开启自动代理,aop注解
        JKD(默认 proxy-target-class="false)
        cglib(proxy-target-class="true")
    -->
    <aop:aspectj-autoproxy proxy-target-class="false" />
</beans>

测试类和第一种方式一样。

10.4、execution()表达式解释

例如: execution(* com.yzh.service..*.*(..))

标识符 含义
execution() 表达式的主体
第一个“*”符号 表示返回值的类型任意
com.yzh.service AOP所切的服务的包名,即,需要进行横切的业务类
包名后面的“..” 表示当前包及子包
第二个“*” 表示类名,*即所有类
.*(..) 表示任意方法名,括号表示参数,两个点表示任意参数类型

12、整合mybatis

步骤:

  1. 导入相关的jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aspectJ AOP织入
    • mybatis-spring【mybatis整合spring需要用到的】
    <dependencies>
        <!--Mysql数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--mybatis相关依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--spring-webmvc(多个spring依赖)-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.21</version>
        </dependency>
        <!--Spring操作数据库的话,还需要一个spring-jdbc的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.19</version>
        </dependency>
        <!--aop织入包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>
        <!--整合spring和mybatis需要的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <!--junit单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    
    <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    
  2. 编写配置文件

  3. 测试

12.1、回忆mybatis

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

12.2、Mybatis-Spring

mybatis-spring官网地址

MyBatis-Spring有相关版本要求,可以去官网具体查询

image-20220725144216385

方式一:传统的方式

  1. 引入Spring配置文件beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
  2. 编写数据源配置

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

    <!--SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定MyBatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:com/yzh/mapper/*Mapper.xml" />
    </bean>
    
  4. SqlSessionTemplate

    <!--SqlSessionTemplate-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>
    
  5. 需要给接口增加实现类

    public class UserMapperImpl implements UserMapper {
    
        //在之前,我们的操作都使用sqlSession来执行,现在使用SqlSessionTemplate
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
    
  6. 将自己写的实现类,注入到Spring中

    <bean id="userMapper" class="com.yzh.mapper.Impl.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession" />
    </bean>
    
  7. 测试使用

    @Test
    public void testSelectUser(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
    

方式二:比较简单

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

  1. 数据源【和第一种方式相同】

  2. SqlSessionFactory【和第一种方式相同】

  3. 给接口增加实现类

    public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    
        public List<User> selectUser() {
            return getSqlSession().getMapper(UserMapper.class).selectUser();
        }
    }
    
  4. 将自己写的实现类,注入到Spring中

    <bean id="userMapper2" class="com.yzh.mapper.Impl.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    
  5. 测试使用

    @Test
    public void testSelectUser2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
    

13、声明式事务

13.1、回顾事务

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

事务ACID原则:

原子性

  • 要么都完成,要么都不完成

一致性

  • 数据和资源总数不变

隔离性

  • 多个业务可能操作同一个资源,防止数据的损坏

持久性

  • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写入到存储器中。

13.2、Spring中的事务管理

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

声明式事务:AOP

  • 一般情况下比编程式事务好用。

  • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。

  • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

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

    xmlns:tx="http://www.springframework.org/schema/tx"
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!--结合AOP实现事务的切入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--给add,update,insert等配置事务-->
    <!--配置事务的传播特性 propagation 默认为REQUIRED-->
    <tx:attributes>
        <tx:method name="add" propagation="REQUIRED" />
        <tx:method name="update" propagation="REQUIRED" />
        <tx:method name="delete" propagation="REQUIRED" />
        <tx:method name="query" read-only="true" />
        <!--一般配置一个*即可-->
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

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

编程式事务管理

  • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚

  • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

思考:为什么需要事务

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

13.3、spring事务传播特性

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

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

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

END

posted @ 2022-07-25 16:27  lyluoye  阅读(35)  评论(0)    收藏  举报