Spring[狂]

写于2021.06.16

视频地址 狂神说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

Spring的各方面地址

  • 官网: https://spring.io/projects/spring-framework#overview
  • 官方下载地址(包括文档): http://repo.spring.io/release/org/springframework/spring
  • GitHub: https://github.com/spring-projectslspring-framework
  • Maven(Spring web MVC) 此处导入webmvc可以将其余衍生包一并导入更方便
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

1.2 优点

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

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

1.3 组成

在这里插入图片描述

1.4 拓展

在Spring的官网有这个介绍,现代化的java开发,就是基于Spring开发

在这里插入图片描述

  • SpringBoot

         一个快速开发的脚手架
    
         基于SpringBoot可以快速开发单个微服务
    
  • Spring Cloud

         SpringCloud使基于SpringBoot实现的
    

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

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

2. IOC理论推导

  1. UserDao 接口
  2. UserDaoImpl 接口实现类
  3. UserService 业务
  4. UserServiceImpl 业务实现类

在我们之前的业务中,业务的需求可能会影响我们的代码,我们需要根据用户的需求去修改源代码

假如程序代码量十分大,我们需要昂贵的成本去修改

  • 主动权在程序员这块⬇

在这里插入图片描述

我们使用一个set接口实现

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

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

  • 主动权在用户手里⬇

在这里插入图片描述

IOC本质

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

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

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

Beans.xml的代码

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

</beans>

3. HelloSpring

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

这个过程就叫控制反转 :

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

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

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

4. IOC创建对象方式

  1. 使用无参构造创建对象【默认】
public User(){
        System.out.println("User的无参构造");
    }
  1. 假设我们要使用有参构造
  • 下标赋值
<!--下标赋值-->
    <bean id="user" class="com.xu.pojo.User">
        <constructor-arg index="0" value="狂神"/>
    </bean>
  • 根据数据类型赋值
<!--根据数据类型赋值,不建议使用-->
    <bean id="user" class="com.xu.pojo.User">
        <constructor-arg type="java.lang.String" value="狂神说"/>
    </bean>
  • 直接通过参数名
<!--直接通过参数名配置-->
    <bean id="user" class="com.xu.pojo.User">
        <constructor-arg name="name" value="狂神说java"/>
    </bean>

5. Spring配置

5.1 别名

<!--别名:如果添加了别名,我们也可以通过别名获取到对象-->
    <alias name="user" alias="dada"/>

5.2 Bean的配置

<!--id:bean的位置标识符,也就是相当于我们学的对象名
          class:bean对象所对应的全限定名:包名+类型
          name:也是别名,erqiename更高级,可以同时取多个外号,
          也可以用多个分隔符如逗号,空格,分号-->
    <bean id="userT" class="com.xu.pojo.UserT" name="user2,u2 u3;u4">
        <property name="name" value="西开"/>
    </bean>

5.3 import

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

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

applicationcontext.xml

  • 小张 benas.xml
  • 小李 beans2.xml
  • 小王 beans3.xml
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

6. 依赖注入(DI)

6.1 构造器注入

在第四章已讲

6.2 set方式注入【重点】

  • 依赖注入:set注入!
  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象的属性,由容器来注入
  1. 复杂类型
public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
  1. 真实测试对象

Student

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 Properties info;
    private String wife;
...
略getset方法与tostring方法

Address

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}
  1. beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.xu.pojo.Student">
        <!--普通值注入,value-->
        <property name="name" value="K"/>
    </bean>

</beans>
  1. 测试类
public class Mytest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
}

完善注入信息

<?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="student" class="com.xu.pojo.Student">
        <!--普通值注入,value-->
        <property name="name" value="K"/>
        <!--bean注入,ref方法-->
        <property name="address" ref="address"/>
        <!--数组注入,利用property子标签里的array数组属性-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--lsit注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>
        <!--map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="111111111111111111"></entry>
                <entry key="银行卡" value="11111111111111111111"></entry>
            </map>
        </property>
        <!--set注入-->
        <property name="games">
            <set>
                <value>lol</value>
                <value>coc</value>
                <value>bob</value>
            </set>
        </property>
        <!--空值注入-->
        <property name="wife">
            <null/>
        </property>
        <!--properties注入-->
        <property name="info">
            <props>
                <prop key="学号">11111111</prop>
                <prop key="性别"></prop>
                <prop key="姓名">小明</prop>
            </props>
        </property>
    </bean>

    <bean id="address" class="com.xu.pojo.Address">
        <property name="address" value="西安"/>
    </bean>
</beans>

6.3 拓展方式注入

我们可以使用p命令和c命令进行注入

官方注释

在这里插入图片描述

使用

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

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

    <!--c命名空间注入,通过构造器注入 construct-args -->
    <bean id="user2" class="com.xu.pojo.User" c:age="18" c:name="狂神学"/>

</beans>

测试:

public void test2(){
        ApplicationContext userbeans = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = userbeans.getBean("user2", User.class);
        System.out.println(user);
}
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

6.4 bean的作用域

在这里插入图片描述

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

产生的对象一致

<bean id="user2" class="com.xu.pojo.User" c:age="18" c:name="狂神学" scope="singleton"/>
  1. 原型模式

每次get产生新的对象

<bean id="user2" class="com.xu.pojo.User" c:age="18" c:name="狂神学" scope="prototype"/>
  1. 其余的request,session,application,这些个只能在web开发中用到

7. Bean的自动装配

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

在Spring中有三种装配方式

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

7.1 测试

  1. 环境搭建
  • 一个人有两个宠物

7.2 ByName自动装配

<bean id="cat" class="com.xu.pojo.Cat"/>
<bean id="dog" class="com.xu.pojo.Dog"/>
<!--byname:会自动到容器上下文查找,和自己对象的set方法后面的值对应的beanid-->
    <bean id="people" class="com.xu.pojo.Person" autowire="byName">
        <property name="name" value="小狂神"/>
    </bean>

例如cat,会到实体类中寻找对应的

在这里插入图片描述

7.3 ByType自动装配

<bean class="com.xu.pojo.Cat"/>
<bean class="com.xu.pojo.Dog"/>
<!--byname:会自动到容器上下文查找,和自己对象属性类型相同的beanid-->
    <bean id="people" class="com.xu.pojo.Person" autowire="byType">
        <property name="name" value="小狂神"/>
    </bean>

小结:

  • 在byname的时候,要保证bean的id唯一,并且这个bean需要和自动注入的属性set方法的值一致
  • 在bytype的时候,要保证所有bean的class唯一【一个class只有一个bean注册】,并且这个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约束
<?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>
  1. 配置注解的支持【重点】
<context:annotation-config/>

@Autowired

直接在属性上使用

@Autowired
    private Cat cat;

也可以在set方法上使用

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

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

科普:

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

测试代码:

public class Person {
    //如果显式的注明require为flase,则这个值可以为null,否则不能为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

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

public class Person {

    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;
    private String name;
}

@Resource注解

public class Person {

    @Resource(name = "cat")
    private Cat cat;
    @Resource
    private Dog dog;
}

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配,都可以放在属性字段上
  • @Autowired通过bytype的方式实现,而且要求这个对象存在【常用】
  • @Resource默认通过byname的方式实现,如果找不到名字,则通过bytype的方式实现,如果两个都找不到,就报错【常用】
  • 执行顺序不同:@Autowired通过bytype的方式实现,@Resource默认通过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:annotation-config/>

</beans>
  1. bean
  2. 属性如何注入
@Component
public class User {

    public String name;

    //相当于 <property name="name" value="狂神"/>
    @Value("狂神")
    public void setName(String name) {
        this.name = name;
    }
}
  1. 衍生的注解

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

  • dao【@Repository】

  • service【@Service】

  • controller【@Controller】

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

  1. 自动装配
@Autowired:自动装配通过类型,名字 
如果Autowired不能唯一装配上属性,则需要通过@Qualifier(value = "xxx")来指定

@Nullable 字段标记了这个注释署名这个值可以为null

@Resource(java原生) 自动装配通过名字,类型
  1. 作用域
@Component
public class User {

    public String name;

    //相当于 <property name="name" value="狂神"/>
    @Value("狂神")
    public void setName(String name) {
        this.name = name;
    }
}
  1. 小结

xml与注解:

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

xml与注解最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.xu"/>
    <context:annotation-config/>

9. 使用java的方式配置Spring

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

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

实体类

//这里这个注解的意思的,就是说明这个类被spring接管,注册到容器中
@Component
public class User {
    private String name;

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

    public String getName() {
        return name;
    }

    @Value("kuangshen") //属性注入值
    public void setName(String name) {
        this.name = name;
    }
    
}

配置文件

@Configuration //这个也会被spring容器托管,注册到容器中,因为他本来就是一个@component ,
// @configuration代表这是一个配置类,就和我们之前的beans.xml
@ComponentScan("com.xu.pojo")
public class MyConfig {

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

测试类

public class Mytest {
    public static void main(String[] args) {
        //如果完全使用配置类方法去做,我们就只能通过annotationconfig上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = context.getBean("user", User.class);

        System.out.println(getUser.getName());
    }
}

错误示范

在这里插入图片描述

正确示范

在这里插入图片描述

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

10. 代理模式

为什么学习代理模式?

因为这就是SpringAOP的底层【SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理
    在这里插入图片描述

10.1 静态代理

角色分析:

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

代码步骤(以租房为例):

  1. 接口
public interface Rent {
    public void rent();
}
  1. 真实角色
//房东
public class Host implements Rent{
    public void rent() {
        System.out.println("房东出租房子");
    }
}
  1. 代理角色
//中介
public class Proxy implements Rent{

    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        seeHouse();
        host.rent();
        hetong();
        fare();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }

    //合同
    public void hetong(){
        System.out.println("签租赁合同");
    }

    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}
  1. 客户端访问代理角色
public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //代理,中介帮房东租房子,中介一般会有附属操作
        Proxy proxy = new Proxy(host);
        //你不用面对房东,直接找中介租房即可
        proxy.rent();
    }
}

代理模式的好处:

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

缺点:

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

10.2 加深理解

聊聊aop

在这里插入图片描述

代码步骤:

  1. 接口
public interface UserService {
    public void add();
    public void del();
    public void update();
    public void query();
}
  1. 实现类
//真实对象
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("增加了一个用户");
    }

    public void del() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void query() {
        System.out.println("查询用户");
    }
}
  1. 当需求增加代码需要改动时,新增一个代理类并实现相对应的功能
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 del() {
        log("del");
        userService.del();
    }

    public void update() {
        log("update");
        userService.update();
    }

    public void query() {
        log("query");
        userService.query();
    }

    //日志方法
    public void log(String msg){
        System.out.println("[Debug]使用了"+msg+"方法");
    }
}
  1. 用户调用代理方法
public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();

        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);

        proxy.del();
    }
}

在公司开发中,改动源代码是大忌,以免业务崩溃,所以引入代理机制

10.3 动态代理

  • 动态代理和静态代理角色相同
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
  • 基于接口——jdk的动态代理【我们主要使用这一种】
  • 基于类:cglib
  • java字节码实现:javassist【主要用于jboss】

需要了解两个类:proxy:代理,invocationHandler:调用处理程序

动态代理的好处:

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

11. AOP

11.1 什么是AOP

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

在这里插入图片描述

11.2 Aop在Spring中的作用

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

以下名词需要了解:

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

在这里插入图片描述

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

在这里插入图片描述

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>
    <scope>runtime</scope>
</dependency>

写一个接口与实现类

UserService

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

UserServiceImpl

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 select() {
        System.out.println("查询到用户");
    }
}

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口:注意点
        UserService userService = (UserService) context.getBean("userService");

        userService.add();
    }
}

方式一:使用SpringAPI接口【主要是SpringAPI接口实现】

  1. 创建log与afterlog

    log引入MethodBeforeAdvice

public class Log implements MethodBeforeAdvice{
    //method:要执行的目标对象的方法
    //objects:参数
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
   afterlog引入AfterReturningAdvice
public class AfterLog implements AfterReturningAdvice{

    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回结果为"+returnValue);
    }
}
  1. 在xml中注册
<!--方式一:使用原生的SpringAPI接口-->
    <!--配置aop:需要导入aop约束-->
    <aop:config>
        <!--切入点:expression:表达式:execution(要执行的位置)-->
        <aop:pointcut id="poincut" expression="execution(* com.xu.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="poincut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="poincut"/>
    </aop:config>

测试

在这里插入图片描述

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

  1. Diy一个aop
public class DiyPointCut {

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

    public void after(){
        System.out.println("==========方法执行后===========");
    }
}
  1. xml中注册
<!--方式二-->
    <bean id="diy" class="com.xu.DIY.DiyPointCut"/>
    <aop:config>
        <!--自动一切面,ref要用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.xu..service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

测试

在这里插入图片描述

方式三:使用注解实现

  1. 创建类并利用注解
//方式三:使用注解实现aop
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

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

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

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.xu..service.UserServiceImpl.*(..))")
    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("=======环绕后========");
    }
}
  1. xml
<!--方式三-->
    <bean id="annotationPointCut" class="com.xu.DIY.AnnotationPointCut"/>
    <!--开启注解支持 JDK(默认proxy-target-class="false") cglib(默认proxy-target-class="true")-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

测试

在这里插入图片描述

我们可以看到环绕前是最先执行的

12. 整合Mybatis

步骤:

  1. 导入相关jar包
  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入
  • mybatis-spring【新包】
  1. 编写配置文件
  2. 测试

12.1 回忆mybatis

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

12.2 Mybatis-Spring

  1. 编写数据源配置
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
  1. sqlSessionFactory
<!--sqlsessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-configure.xml"/>
        <property name="mapperLocations" value="classpath:com/xu/mapper/*.xml"/>
    </bean>
  1. sqlSessionTemplate
<!--SqlSessionTemplate:就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能选用构造器注入sqlSessionFactory,因为他没有set方法注入参数-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
  1. 需要给接口增加实现类
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();
    }
}
  1. 将自己写的实现类注入到spring中
<bean id="userMapper" class="com.xu.mapper.UserMapperImpl">
        <property name="sqlsession" ref="sqlSession"/>
    </bean>
  1. 测试使用即可
public class MyTest {
    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper1", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}

在这里插入图片描述

方法二【利用SqlSessionDaoSupport】:

前三步与上面一致

  1. 给接口增加实现类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}
  1. 将自己写的实现类注入到spring中
<bean id="userMapper2" class="com.xu.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  1. 测试使用
public class MyTest {
    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}

在这里插入图片描述

13. 声明式事务

13.1 回顾事务

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

事务ACID原则:

  • A:原子性
  • C:一致性
  • I:隔离性 :多个事务可能操作同一个资源,防止数据损坏
  • D:持久性:事务一旦提交,无论发生什么问题,结果都不会再被影响,被持久化写到容器中

13.2 spring中的事务管理

  • 声明式事务:aop
  • 编程式事务:try/catch

步骤:

  1. 在头部文件开启tx
xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd"
  1. 在xml中编织
<!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
    <!--结合aop实现事务的织入-->
    <!--配置事务通知:-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务传播特性:new propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

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

xml中编织事务代码完全不影响原业务代码,更灵活

思考:

为什么需要事务

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值