当前位置:首页>笔记分享>Java笔记>Spring5

Spring5



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!

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

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

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

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.10</version>
</dependency>
<!--spring-webmvc比较大 maven可以帮助我们下载依赖的包
spring-jdbc是整合Mybatis用的
-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.10</version>
</dependency>

1.2、 优点

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

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

1.3、 组成

Spring七大模块

七大模块

1.4、 拓展

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

image-20220125194653879

未来需要了解的:

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

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

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

2、 IOC理论推导

之前的流程

  1. UserDao 接口

  2. UserDaoImpl 实现类

  3. UserService 业务接口

  4. UserServiecImpl 业务实现类

    image-20220316103126402

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

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

private UserDao userDao;//利用set进行动态实现值的注入!
        public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
        }
  • 之前,程序是主动创建对象!控制权在程序猿手上!
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!

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

IOC本质

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

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

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

3、 Hello 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 使用Spring来创建对象 在Spring中这些都称为Bean
       等价的Hello hello = new Hello()
       id = 变量名
       class = new的对象
       property = 给对象中的属性设置值
       value = 附基本类型的值
       ref = 引用Spring容器中创建好的对象
    -->
    <bean id="hello" class="com.gong.pojo.Hello">
        <property name="str" value="小鹏"></property>
    </bean>
</beans>

编写POJO

package com.gong.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }
        //set必须有
    public void setStr(String str) {
        this.str = str;
    }

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

测试

import com.gong.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

        //获取ApplicationContext拿到Spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //容器在手天下我又,需要什么get什么
        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. 使用无参构造创建对象,默认!

  2. 假设我们要使用有参构造创建对象(三种方法)。

  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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user" class="com.gong.pojo.User">
        <constructor-arg index="0" value="小鹏"></constructor-arg>
    </bean>
</beans>
  1. 类型
<!--方法二:类型-->
<bean id="user" class="com.gong.pojo.User">
        <constructor-arg type="java.lang.String" value="小鹏2">
            </constructor-arg>
</bean>
  1. 参数名
<!--方法3:参数名(推荐)-->
<bean id="user" class="com.gong.pojo.User">
        <constructor-arg name="name" value="小鹏3"></constructor-arg>
</bean>

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

5、 Spring配置

5.1、 别名

<!--别名,如果添加了别名,我们也可以用别名获取到这个对象-->
<alias name="userT" 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合并为一个总的!

  • 张三

  • 李四

  • 王五

  • applicationContext.xml(总的 )

  <!--将所有人的导入到一个总的-->
  <import resource="beans1.xml"></import>
  <import resource="beans2.xml"></import>
  <import resource="beans3.xml"></import>

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

6、 依赖注入

6.1、 构造器注入

前面已经说过了

6.2、 Set方法注入 【重点】

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

【环境搭建】

  1. 复杂类型
package com.gong.pojo;

public class Address {
    private String 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 + '\'' +
                '}';
    }
}
  1. 真实测试对象
package com.gong.pojo;

import java.util.*;

public class Student {
    private Address address;
    private String[] book;
    private String name;
    private List<String> hobbys;
    private Map<String, Object> card;
    private Set<String> games;
    private String wife;
    private Properties info;
   //再加上getset
}
  1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.gong.pojo.Address">
        <property name="address" value="xx省xx市"></property>
    </bean>
    <bean id="student" class="com.gong.pojo.Student">
        <!--基本类型-->
        <property name="name" value="小鹏"></property>
        <!--引用类型-->
        <property name="address" ref="address"></property>
        <!--数组-->
        <property name="book">
            <array>
                <value>Java核心技术卷</value>
                <value>西瓜书</value>
                <value>南瓜书</value>
                <value>深度学习</value>
            </array>
        </property>
        <!--列表-->
        <property name="hobbys">
            <list>
                <value>吃</value>
                <value>喝</value>
                <value>玩</value>
            </list>
        </property>
        <!--map-->
        <property name="card">
            <map>
                <entry key="学生卡" value="21212060803"></entry>
                <entry key="银行卡" value="123124123123123123"></entry>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>王者农药</value>
            </set>
        </property>
        <!--null-->
        <property name="wife">
            <null/>
        </property>
        <!--prop-->
        <property name="info">
            <props>
                <prop key="性别">男</prop>
                <prop key="学号">170809011044</prop>
            </props>
        </property>
    </bean>

</beans>

也就map和props格式不太一样

  1. 测试类
import com.gong.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student)context.getBean("student");
        System.out.println(student.toString());
        /**
         *
         * Student{
         * address=Address{address='xx省xx市'},
         * book=[Java核心技术卷, 西瓜书, 南瓜书, 深度学习],
         * name='小鹏', hobbys=[吃, 喝, 玩],
         * card={学生卡=21212060803, 银行卡=123124123123123123},
         * games=[LOL, COC, 王者农药],
         * wife='null',
         * info={学号=170809011044, 性别=男}}
         * **/
    }
}

6.3、 拓展方式注入

我们可以使用P命名空间和C命名空间进行注入

使用:

前面还包括一个User实体类就不写了

<?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命名空间注入(无惨构),可以直接注入属性的值:property-->
    <bean id="user" class="com.gong.pojo.User" p:age="18" p:name="小鹏"></bean>
    <!--c命名空间注入(要有参构造),通过构造器注入:construct-args-->
    <bean id="user2" class="com.gong.pojo.User" c:age="19" c:name="大鹏"></bean>
</beans>

测试:

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

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

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

6.4、 bean的作用域

Scope Description
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.xia.pojo.User" p:age="18" p:name="王小姐" scope="singleton"></bean>
  1. 原型模式:每一次从容器中get的时候,都会产生一个新的对象
<bean id="user" class="com.xia.pojo.User" p:age="18" p:name="王小姐" scope="prototype"></bean>

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

7、 Bean的自动装配

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

在Spring中有三种装配的方式

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

7.1、 测试

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

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

    <bean id="dog" class="com.gong.pojo.Dog"/>
    <bean id="cat" class="com.gong.pojo.Cat"/>
    <!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!-->
    <bean id="user" class="com.gong.pojo.User" autowire="byName">
        <property name="name" value="小鹏"></property>
        <!--cat和dog属性会根据setxxx方法的xxx在上下文寻找对应id自动装配-->
    </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"
       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">

    <bean id="dog" class="com.gong.pojo.Dog"/>
    <bean id="cat" class="com.gong.pojo.Cat"/>
    <!--byType:会自动在容器上下文查找,和自己对象属性类型相同的bean!-->
    <bean id="user" class="com.gong.pojo.User" autowire="byType">
        <property name="name" value="小鹏"></property>
     <!--cat和dog属性会根据上下文找想通过类型装配-->
    </bean>
</beans>
public class Cat {
    public void shout(){
        System.out.println("喵喵~");
    }
}
=======================
public class Dog {
    public void shout(){
        System.out.println("旺旺~");
    }
}
======================
public class User {

    private String name;
    //如果现实定义了Autowired的required属性为false,说明这个对象可以为null 一般用不到
    @Resource
    private Cat cat;
    @Resource(name = "dog222")
    private Dog dog;

    public String getName() {
        return name;
    }
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }

}

小结:

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

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

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

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

要使用注解须知:

配置

  1. 导入约束:context约束

  2. 配置注解的支持:<context:annotation-config/>

   <?xml version="1.0" encoding="UTF-8"?>
   <beans xmlns="http://www.springframework.org/schema/beans"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:context="http://www.springframework.org/schema/context"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans
                 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>

@Autowired

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

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

科普:

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

测试代码

<?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">
    <bean id="dog" class="com.gong.pojo.Dog"/>
    <bean id="dog222" class="com.gong.pojo.Dog"/>
    <bean id="cat" class="com.gong.pojo.Cat"/>
    <bean id="user" class="com.gong.pojo.User"/>
<context:annotation-config/>
</beans>
package com.gong.pojo;

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

public class User {
    private String name;
    //如果现实定义了Autowired的required属性为false,说明这个对象可以为null 一般用不到
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")//如果有多个对象,可以通过Qualifier指定对象
    private Dog dog;
    public String getName() {
        return name;
    }
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
}

测试

import com.gong.pojo.User;
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");
        User user = context.getBean("user", User.class);
        user.getCat().shout();
        user.getDog().shout();
    }
}   

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

public class User{
@Autowired
@Qualifier(value = "dog2")
private Dog dog;
@Autowired
@Qualifier(value = "cat2")
private Cat cat;}

@Resource注解

package com.gong.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.annotation.Resource;
public class User {
    private String name;
    @Resource
    private Cat cat;
    @Resource(name = "dog222")
    private Dog dog;
    public String getName() {
        return name;
    }
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
}

小结:

@Autowired和@Resource的区别:

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

  • @Autowired先通过byType的方式实现,找不到再通过byName实现

    • 如果不能唯一装配,则需要通过@Qualifier(value = “xxx”)
  • @Resource 先通过byName的方式实现,找不到再通过byType实现,如果都找不到的情况下,就会报错【常用】(可根据name指定唯一)

  • 执行顺序不同:@Autowired先通过byType,@Resource先通过byName

8、 使用注解开发

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

-20220318091914772

使用注解需要导入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
              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:component-scan base-package="com.gong.pojo"/>
    <!--context约束-->
    <context:annotation-config/>
</beans>
  1. bean
    • @Component:组件,放在类上说明这个类被Spring管理了,就是bean
  2. 属性如何注入
package com.gong.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价在配置文件中的bean
@Component
public class User {
    //等价在配置文件中给属性赋值,如果有set方法注解也可以写在set方法上
    @Value("小鹏")
    public String name;
    //@Value("小鹏")
    public void setName(String name) {
        this.name = name;
    }
}
  1. 衍生的注解

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

    • dao层 @Repository

    • service @Service

    • controller @Controller

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

  2. 自动装配

    上面有说详细

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

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

@Component
//作用域
@Scope("prototype")
public class User {
    @Value("小鹏")
    public String name;
    }
  1. 小结

    xml与注解:

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

    xml与注解最佳实践:

    • xml用来管理bean。

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

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

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

9、 使用Java的方式配置Spring

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

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

Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的:

  1. @Configuration 作用于类上,相当于一个xml配置文件;

  2. @Bean 作用于方法上,相当于xml配置中的<bean>

当@Bean 注解使用在方法上面是,会被spring自动作为一个bean进行注入,

bean的类型为该方法的返回类型,bean的id为方法名称。方法参数会通过spring自动注入。

实体类

package com.gong.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这个注解,就是说明这个类被Spring接管,注册在容器了
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value("小鹏")//属性注入
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置文件

package com.gong.config;

import com.gong.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;
//@Configuration表示这个也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和beans.xml(配置文件)一样
@Configuration
@ComponentScan("com.gong.pojo")//指定要扫描的包,这个包下的注解就会生效
@Import(gongConfig2.class)//将其他配置文件导入到这个
public class gongConfig {
    /*注册一个bean,就相当于我们写一个bean标签
     这个方法的名字,就相当于bean标签中的id属性
     这个方法的返回值,就相当于bean标签中的class属性
     */
    @Bean
    public User user(){
        return  new User();//就是返回要注入到bean的对象
    }
}

测试类!

import com.gong.config.gongConfig;
import com.gong.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

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

10、 代理模式

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

面试必问Springaop和Springmvc

10.1、 静态代理

image-20220318171312128

角色分析:

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

代码步骤:

  1. 接口

    package com.gong.client;
    //租房
    public interface Rent {
       void rent();
    }
  2. 真实角色

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

    package com.gong.client;
    
    public class Proxy implements Rent {
       private Landlord landlord;
    
       public Proxy(Landlord landlord){
           this.landlord = landlord;
       }
       public void setLandlord(Landlord landlord) {
           this.landlord = landlord;
       }
    
       public void rent() {
           landlord.rent();
           seeHouse();
           fee();
           heTong();
       }
       //代理附属能力
       public void seeHouse() {
           System.out.println("看房");
       }
    
       public void fee() {
           System.out.println("收中介费");
       }
    
       public void heTong() {
           System.out.println("签合同");
       }
    }
    
  4. 客户端访问代理角色

    package com.gong.client;
    
    public class Client {
       public static void main(String[] args) {
           //房东有房子要出租
           Landlord landlord = new Landlord();
           //通过代理租房,但代理一般会有一些附属操作
           Proxy proxy = new Proxy(landlord);
           //不用见房东 通过代理租房
           proxy.rent();
       }
    }
    

代理模式的好处:

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

缺点:

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

10.2、 加深理解

当我们需要对原有功能进行增加日志的时候,为了不更改原有代码,则需要代理来增加附属日志功能

  1. Service接口

    package com.gong.demo02;
    
    public interface UserService {
       void add();
       void delete();
       void update();
       void query();
    }
    
  2. Service实现

    package com.gong.demo02;
    
    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. 代理

    package com.gong.demo02;
    
    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("执行了"+msg+"方法");
       }
    }
    
  4. 客户端

    package com.gong.demo02;
    
    public class Client {
       public static void main(String[] args) {
           UserServiceImpl userService = new UserServiceImpl();
    
           UserServiceProxy userServiceProxy = new UserServiceProxy();
           userServiceProxy.setUserService(userService);
           //代理执行
           userServiceProxy.add();
       }
    }

浅聊AOP

image-20220319091713216

10.3、 动态代理

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

需要了解两个类:

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

动态代理的好处:

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

可以当成模板只用改变target即可

package com.gong.demo03;

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;
    }
    //生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this);
    }
    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(target, args);
        return result;
    }
}

Proxy.newProxyInstance方法中,共有三个参数:

  1. this.getClass().getClassLoader()目标对象通过getClass方法获取类的所有信息后,调用getClassLoader()方法来获取类加载器。获取类加载器后,可以通过这个类型的加载器,在程序运行时,将生成的代理类加载到JVM即Java虚拟机中,以便运行时需要!
  2. target.getClass().getInterfaces()获取被代理类的所有接口信息,以便于生成的代理类可以具有代理类接口中的所有方法。
  3. this:我们使用动态代理是为了更好的扩展,比如在方法之前做什么,之后做什么等操作。这个时候这些公共的操作可以统一交给代理类去做。这个时候需要调用实现了InvocationHandler 类的一个回调方法。由于自身变实现了这个方法,所以将this传递过去。

invoke方法的参数

  1. Object proxy生成的代理对象,就是我们生成的代理类。
  2. Method method:被代理的对象中被代理的方法的一个抽象。
  3. Object[] args:被代理方法中的参数。这里因为参数个数不定,所以用一个对象数组来表示。

测试

package com.gong.demo03;

import com.gong.demo02.UserService;
import com.gong.demo02.UserServiceImpl;

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

11、 AOP(超级重点)

一句话说就是不影响之前业务类的情况下进行业务增强

11.1、 什么是AOP

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

image-20220319113345127

11.2、 AOP在Spring中的作用

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

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

image-20220319150600094

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

image-20220319113832872

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

11.3、 使用Spring实现AOP

功能最完善

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

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

方式一: 使用Spring的API接口

【主要SpringAPI接口实现】

  1. 实现AfterReturningAdvice接口
package com.gong.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
     */
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"对象执行了"+method.getName()+"方法,返回值为:"+returnValue);
    }
}
  1. 实现MethodBeforeAdvice接口
package com.gong.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class BeforeLog implements MethodBeforeAdvice {
    /**
     * @param method 要执行的目标对象方法
     * @param args 参数
     * @param target 目标对象
     * @throws Throwable
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"对象执行了"+method.getName()+"方法");
    }
}
  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"
       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
        https://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    注册bean-->
    <bean id="userService" class="com.gong.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.gong.log.BeforeLog"/>
    <bean id="afterLog" class="com.gong.log.AfterLog"/>
<!--    方式一:使用原生Spring-API接口-->
<!--    配置aop:需要导入aop约束-->
    <aop:config>
        <!--切点 expression:表达式,execution(要执行过的位置)-->
        <aop:pointcut id="pointcut1" expression="execution(* com.gong.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加  将类xxx切入到切入点xxx-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut1"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut1"/>
    </aop:config>
</beans>
  1. 测试
import com.gong.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //代理模式只能代理接口  转换成实体类就会报错
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

补充:关于execution是表达式

语法:execution(修饰符  返回值  包.类.方法名(参数) throws异常)

修饰符,一般省略

  • public:公共方法

  • *:任意

返回值,不能省略

  • void:返回没有值
  • String:返回值字符串
  • *:任意

包,[可省略]

  • com.gong:固定包
  • com.gong.*.service:gong包下面子包任意 (例如:com.gong.staff.service)
  • com.gong.. :gong包下面的所有子包(含自己)
  • com.gong.*.service..:gong包下面任意子包,固定目录service,service目录任意包

类,[可省略]

  • UserServiceImpl:指定类
  • *Impl:以Impl结尾
  • User*: 以User开头
  • *:任意

方法名,不能省略

  • addUser:固定方法

  • add* :以add开头

  • Do* : 以Do结尾

  • * :任意

(参数)

  • () :无参

  • (int) :一个整型

  • (int ,int) :两个

  • (..) :参数任意

throws ,可省略,一般不写。

案例:

execution(* com.gong.*.service..*.*(..))

方式二: 使用自定义类来实现AOP

【主要是切面定义】

  1. 定义接口diy
package com.gong.diy;

public class DiyPointCut {
    public void before(){
        System.out.println("=======方法之前=======");
    }
    public void after(){
        System.out.println("=======方法之后=======");
    }
}
  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"
       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
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--注册bean-->
    <bean id="userService" class="com.gong.service.UserServiceImpl"/>
    <!--方法二:自定义类来实现AOP-->
    <bean id="diy" class="com.gong.diy.DiyPointCut"/>
   <!--配置aop:需要导入aop约束-->
    <aop:config >
        <!--自定义切面 ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切点-->
            <aop:pointcut id="point" expression="execution(* com.gong.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

方式三: 使用注解实现

编写AnnotationPointCut类

package com.gong.diy;

import org.aspectj.lang.ProceedingJoinPoint;
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 AnnoPointCut {
    @Before("execution(* com.gong.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法前");
    }
    @After("execution(* com.gong.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法后");
    }
    @Around("execution(* com.gong.service.UserServiceImpl.*(..))")
    public void round(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proceed = pj.proceed();
        System.out.println("环绕后");
        //获得签名信息 没啥用看看就行
        System.out.println(pj.getSignature());
    }
}

开启注解支持

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

    <!--注册bean-->
    <bean id="userService" class="com.gong.service.UserServiceImpl"/>
    <!--方式三:注解-->
    <bean id="annoPointCut" class="com.gong.diy.AnnoPointCut"/>
    <!--开启注解支持! JDK(默认 proxy-target-class="false")
     cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>
</beans>

12、 整合Mybaits

12.1、 回忆Mybatis

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>Spring-study</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Spring-10-Mybatis</artifactId>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.10</version>
        </dependency>
        <!--Spring操作数据库还需要一个包-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.17</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <!--mybatis和Spring整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>
    <!-- 在build中配置resources,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案: -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

1.编写实体类

package com.gong.pojo;

import lombok.Data;

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

2.编写核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias type="com.gong.pojo.User" alias="user"/>
    </typeAliases>
    <environments default="development">
        <!--        可以有多个根据id区分-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/JavaStudy?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/gong/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

3.编写接口

package com.gong.mapper;

import com.gong.pojo.User;

import java.util.List;

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

4.编写Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace是对应的实现接口-->
<mapper namespace="com.gong.mapper.UserMapper">

    <!--查询语句,id对应方法名,resultMap为返回结果 resultType返回类型-->
    <select id="selectUser" resultType="user">
        select * from JavaStudy.Mybatis_study_user;
    </select>
</mapper>

5.测试

import com.gong.mapper.UserMapper;
import com.gong.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyTest {
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = build.openSession(true);

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

12.2、 Mybatis-Spring

实现方法一

步骤:

  1. 编写数据源配置
  2. 编写SqlSessionFactory
  3. 编写SqlSessionTemlate(步骤123都是固定的)
  4. 需要给接口加实现类
  5. 测试

详细代码Spring-10-Mybatis

  1. 编写数据源配置
   <!--DataSource:数据源使用Spring的数据源替换Mybatis的配置 之前见过的数据源有c3p0和dbcp
   我们这里使用Spring提供的JDBC rg.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/JavaStudy?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
           <property name="username" value="root"/>
           <property name="password" value="12345678"/>
       </bean>
  1. SqlSessionFactory
   <!--sqlSessionFactory,创建sqlSession用的-->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <property name="dataSource" ref="dataSource"/>
           <!--绑定Mybatis配置文件 其实Spring都可以做到可不-->
           <property name="configLocation" value="classpath:mybatis-config.xml"/>
         <!--相当于Mybatis中的映射-->
           <property name="mapperLocations" value="classpath:com/gong/mapper/*.xml"/>
       </bean>
  1. SqlSessionTemlate
   <!--SqlSessionTemplate:就是我们使用的sqlSession-->
       <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
           <!--没有set所以只能构造器注入-->
           <constructor-arg index="0" ref="sqlSessionFactory"/>
       </bean>
  1. 需要给接口加实现类
   package com.gong.mapper;

   import com.gong.pojo.User;
   import org.mybatis.spring.SqlSessionTemplate;
   import java.util.List;

   public class UserMapperImpl implements UserMapper {
       //我们所有的操作,都是用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();
       }
   }
   <!--实体类beans-->
       <bean id="userMapper" class="com.gong.mapper.UserMapperImpl">
           <property name="sqlSession" ref="sqlSession"/>
       </bean>
  1. 测试
   import com.gong.mapper.UserMapper;
   import com.gong.mapper.UserMapperImpl;
   import com.gong.pojo.User;
   import org.junit.Test;
   import org.springframework.context.ApplicationContext;
   import org.springframework.context.support.ClassPathXmlApplicationContext;

   import java.io.IOException;
   import java.util.List;

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

实现方法二

继承SqlSessionDaoSupport 实现

package com.gong.mapper;

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

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    //继承SqlSessionDaoSupport可以直接getSqlSession() 不需要利用set注入SqlSessionTemplate
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

配置bean

    <!--SqlSessionDaoSupport 可以直接省略一步sqlSession直接给sqlSessionFactory就行-->
    <bean id="userMapper2" class="com.gong.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

测试

import com.gong.mapper.UserMapperImpl2;
import com.gong.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;

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

13、 声明式事务

13.1、 事务回顾

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

事务的ACID原则:

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

13.2、 Spring中的事务管理

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

思考

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况:
  • 如果我们不在Spring中配置声明式事务,我们就需要到代码中手动配置事务
  • 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题,不能马虎。
<!--完整代码在Spring-11-transaction-->
<!--测试是添加用户以及删除用户先添加如果删除失败则回滚不能添加用户-->
    <!--配置声明式事务-->
    <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>
            <!--name写方法名无效不知道为什么 还是通用*才行-->
           <tx:method name="addUser" propagation="REQUIRED"/><!--name值可以写*则代表所有方法-->
            <tx:method name="delUser" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
<!--            <tx:method name="query" read-only="true"/><!–只读–>-->
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.gong.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

给TA打赏
共{{data.count}}人
人已打赏
Java笔记笔记分享

Mybatis

2022-1-4 20:14:15

Java笔记笔记分享

SpringMVC

2022-2-1 21:23:36

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
购物车
优惠劵
有新私信 私信列表
搜索