Spring 5笔记(超长,完结)

image-20200531213054908

学习资源来自于哔哩哔哩UP遇见狂神说,一个宝藏UP大家快去关注吧!记得三连加分享,不要做白嫖党.

由于使用的是国外的imgur图床,图片无法显示请魔法上网 !

由于使用的是国外的imgur图床,图片无法显示请魔法上网 !

由于使用的是国外的imgur图床,图片无法显示请魔法上网 !

1. Spring 5

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://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/overview.html#overview

Spring Framework 文档 : https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/

Spring所有版本下载地址 : https://repo.spring.io/release/org/springframework/spring/

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

Maven : (由于我比较怂,不敢用最新版,所以用和老师一样的版本)

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

1.2 优点

  • Spring是一个开源的免费的框架(容器)!
  • Spring是一个轻量级的、非入侵式的框架!
  • 控制反转(IOC),I面向切面编程(AOP)!
  • 支持事务的处理,对框架整合的支持!
IOC,英文全称Inversion of Control,意为控制反转。 AOP,英文全称Aspect-Oriented Programming,意为面向切面编程 .

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

1.3 组成

image-20200613164138620

1.4 拓展

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

img

  • Spring Boot。一个快速开发的脚手架。

    • 基于SpringBoot可以快速的开发单个微服务。
    • 约定大于配置!
  • Spring Cloud

    • Springcloud 是基于SpringBoot实现的。

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

弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱" (所以出来了SpringBoot)

2. IOC理论推导

之前写法 :

  1. UserDao

  2. UserDaoImpl

  3. UserService

  4. UserServiceImpl

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

在业务层我们使用private UserDao userDao = new UserDaoImpl(); 来获取Dao层的方法,如果用户的需求增加,我们需要添加UserDao接口的实现类,但是这样就得改业务层的代码. 如果每次需求都得修改原码,这样的代价是十分昂贵的 !

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

UserServiceImpl.java

public class UserServiceImpl implements UserService {

    private UserDao userDao;

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

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

}

MyTest.java

public class MyTest {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();

        userService.setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
    }
}

userService.setUserDao(new UserDaoMysqlImpl());

这样只需要在测试类中选择实例哪个业务层实现类,而不需要修改源代码.

  • 之前,程序是主动创建对象 ! 控制权在程序员手上!
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!

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

IOC本质

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

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

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

3. HelloSpring

Spring core文档 里面找到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">


</beans>

pojo :

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

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

ApplicationContext.xml :

<bean id="hello" class="com.tan.pojo.Hello">
    <property name="str" value="Hello Spring!"/>
</bean>

MyTest :

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象!
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //我们的对象现在都在Spring中管理了,我们要使用,直接去里面拿就可以了!
        Object hello = context.getBean("hello");
        System.out.println(hello.toString());
    }
}

输出: Hello{str='Hello Spring!'}

从中我们可以看到并没有将需实例的对象new出来,而是配置了一个bean ,我们只需要的东西可以直接从容器中获取.

  • 要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC就是: 对象由Spring来创建,管理,装配 !

4. IOC创建对象的方式

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

  2. 假如我们要使用有参构造创建对象

    1. 下标赋值

      <!--第一种下标赋值-->
      <bean id="user" class="com.tan.pojo.User">
          <constructor-arg index="0" value="有参构造的下标赋值"/>
      </bean>
      
    2. 通过类型创建

      <!--第二种方式,通过类型创建,不建议使用-->
      <bean id="user" class="com.tan.pojo.User">
          <constructor-arg value="通过类型船舰" type="java.lang.String"/>
      </bean>
      
    3. 直接通过参数名来设置

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

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

5. Spring配置

5.1 别名

<alias name="user" alias="这里可以取别名"/>

5.2 Bean的配置

<!--
id : bean 的唯一标识符,也就是相当于我们学的对象名
class : bean 对象所对应的全限定名:包名 + 类型
name :也是别名,而且name 可以同时取多个别名,可以用逗号,空格,分号分割
-->
<bean id="userT" class="com.tan.pojo.UserT" name="t,userT2 u3;u4">
        <property name="name" value="hello"/>
</bean>

5.3 import

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

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

  • 张三
  • 李四
  • 王五
  • applicationContext.xml

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

image-20200614095903765

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

6. 依赖注入(DI)

6.1 构造器注入

就是第4点中有无参构造和有参构造的区别.

6.2 set方式注入[重点]

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

[环境搭建,注入流程]

  1. 复杂类型

    public class Address {
        String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
    
  2. 真实注入对象

    @Data
    public class Student {
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbies;
        private Map<String, String> card;
        private Set<String> games;
        private Properties info;
        private String wife;
    }
    
  3. 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">
    
        <!--第一种普通注入,value-->
        <bean id="student" class="com.tan.pojo.Student">
            <property name="name" value="tanshishi"/>
        </bean>
        
    </beans>
    
  4. 测试类

    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.getName());
        }
    }
    
  • idea会智能提醒没有注入的属性 :

image-20200614113210954

  • 与实体类属性一一对应后的完整的ApplicationContext.xml :
    实体类中的属性:

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String, String> card;
    private Set<String> games;
    private Properties info;
    private String wife;
    
<bean id="address" class="com.tan.pojo.Address">
    <property name="address" value="地址"/>
</bean>

<bean id="student" class="com.tan.pojo.Student">
    <!--第一种普通注入,value-->
    <property name="name" value="tanshishi"/>
    <!--第二种Bean注入,ref-->
    <property name="address" ref="address"/>
    <!--数组-->
    <property name="books">
        <array>
            <value>红楼梦</value>
            <value>西游记</value>
            <value>水浒传</value>
            <value>三国演义</value>
        </array>
    </property>
    <!--List-->
    <property name="hobbies">
        <list>
            <value>bilibili</value>
            <value>youtube</value>
            <value>java</value>
            <value>games</value>
        </list>
    </property>
    <!--Map-->
    <property name="card">
        <map>
            <entry key="校园卡" value="1809101020"/>
            <entry key="身份证" value="1534613846384"/>
            <entry key="银行卡" value="43543543812435"/>
        </map>
    </property>
    <!--Set-->
    <property name="games">
        <set>
            <value>R6s</value>
            <value>dying light</value>
            <value>the witcher 3</value>
        </set>
    </property>
    <!--Properties-->
    <property name="info">
        <props>
            <prop key="driver">??????</prop>
            <prop key="url">www.baidu.com</prop>
            <prop key="username">root</prop>
            <prop key="password">123456</prop>
        </props>
    </property>
    <!--null-->
    <property name="wife">
        <null/>
    </property>
</bean>

toString输出 :

Student{
    name='tanshishi', 
    address=Address{address='地址'},
    books=[红楼梦, 西游记, 水浒传, 三国演义], 
    hobbies=[bilibili, youtube, java, games],
    card={
        校园卡=1809101020, 
        身份证=1534613846384,
        银行卡=43543543812435
    }, 
    games=[R6s, dying light, the witcher 3], 
    info={
        password=123456,
        driver=??????,
        url=www.baidu.com, 
        username=root
    }, 
    wife='null'}

主要是第一种和第二种.

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.tan.pojo.User" p:age="19" p:name="tan"/>

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


</beans>

测试:

@Test
public void test2() {
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2", User.class);

    System.out.println(user.toString());
}

注意:

  • 需要先导入约束

    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:c="http://www.springframework.org/schema/c"
    
  • c标签和p标签不能写在一起.

6.4. bean的作用域(scope)

Imgur

  1. 单例模式(Spring默认机制,在同一个bean中创建的实例都是同一个对象)
    Imgur

     <bean id="user2" class="com.tan.pojo.User" c:name="cname" c:age="20" scope="singleton"/>
    

    单例模式问题: 并发的时候可能会产生延迟,或者数据不一致

  2. 原型模式(每次从"容器"中get都会获得新的对象)

    Imgur

    <bean id="user2" class="com.tan.pojo.User" c:name="cname" c:age="20" scope="prototype"/>
    

    测试:

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2", User.class);
        User user2 = context.getBean("user2", User.class);
    
        System.out.println(user == user2);
    }
    
    结果: false
    

    原型模式问题: 特别浪费资源

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

7. bean的自动装配

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

在Spring中有三种装配的方式

  • 在xml中显示的装配
  • 在java中显示装配
  • 隐式地自动装配bean [重要]

7.1 测试

环境搭建 : Imgur

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

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

7.2 ByName自动装配

Imgur

在ref引用对象的时候,发现名字基本一样,引用的却要多写一行引用的代码. 于是我们可以用Spring的byBame自动装配.

Imgur

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

<!--
byName : 会自动在容器上下文查找和自己对象set方法后面的值对应的bean id
-->
<bean id="people" class="com.tan.pojo.People" autowire="byName">
    <property name="name" value="tan"/>
</bean>

实现原理:

byName : 会自动在容器上下文查找和自己对象set方法后面的值对应的bean id

也就是这个位置: image-20200615103238899

并且<bean id="cat" class="com.tan.pojo.Cat"/>中id的值只能识别小写.

7.3 ByType自动装配

<bean class="com.tan.pojo.Cat"/>
<bean class="com.tan.pojo.Dog"/>

<!--
byName : 会自动在容器上下文查找 和自己对象set方法后面的值对应的bean id
byType : 会自动在容器上下文查找 和自己对象属性类型相同的bean
-->
<bean id="people" class="com.tan.pojo.People" autowire="byType">
    <property name="name" value="tan"/>
</bean>

小结 :

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

7.4 使用注解实现自动装配

配置环境:

  1. 导入约束: context约束

    Imgur

<?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使用 : **

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

image-20200615110015689

ApplicationContext.xml中只需要这样写 :

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

注意点:

使用Autowired我们可以不用写set方法,因为它是通过反射获取的,所以前提是自动装配的属性在IOC容器中存在,且符合属性byType .

拓展:

@Autowired(required = false)
@Qualifier(value = "cat2")
private Cat cat;

@Autowired(required = false)
@Qualifier(value = "dog2")
private Dog dog;
private String name;
  • 如果字段想设置可为空: @Autowired(required = false)
  • 由于@Autowired是byType自动装配,属性名必须与bean中的id匹配,且只能单一匹配. 可以用@Qualifier(value = "xxx") 来指定实现装配的值.
  • @Qualifier 可以让@Autowired的自动装配改为ByName自动装配
  • 其装配规则为:
    @Autowired = byType,@Autowiredxxx+@Qualifier = byType || byName

小结:

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

8. 使用注解开发

maven依赖:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

ApplicationContext.xml添加contex支持:

<?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.tan"/>
    <context:annotation-config/>



</beans>
  1. bean

  2. 属性如何注入

    //@Component 组件
    //等价于: <bean id="user" class="com.tan.dao.User"/>
    @Component
    public class User {
    
        @Value("tan")
        public String name;
    }
    
  3. 衍生的注解

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

    • dao [@Repository]

    • service [Service]

    • controller [Controller]

      与@Component一样,声明这个类是Spring下mvc三层架构中的一某层

  4. 自动装配
    @Autowired , 详见7.4

  5. 作用域
    @Scope("singleton")

    @Component
    @Scope("singleton")
    public class User {
    
        @Value("tan")
        public String name;
    }
    
  6. 小结
    xml与注解 :

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

    xml与注解最佳实践:

    • xml 用来管理bean;
    • 注解只负责完成属性的注入;
    • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

9. 使用Java的方式配置Spring

完全不使用Spring的xml配置,全权交给Java来做 .

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

Imgur

实体类 User :

@Component
public class User {
    
    private String name;

    public String getName() {
        return name;
    }

    @Value("tan")
    public void setName(String name) {
        this.name = name;
    }

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

配置类 MyConfig :

//这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
//@Configuration 代表这是一个配置类,和ApplicationContext.xml是一样的
@Configuration
@ComponentScan("com.tan.pojo")
@Import(MyConfig2.class)
public class MyConfig {

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

测试类 Test :

public class MyTest {
    public static void main(String[] args) {
        //通过AnnotationConfigApplicationContext 上下文获取容器,通过配置类的class对象加载 .
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("getUser", User.class);

        System.out.println(user.getName());

    }
}

纯Java的配置方式 , 在SpringBoot中随处可见 !

10. 代理模式

为什么要学代理模式 ? 因为这就是SpringAOP的底层 ! [面试必问: SpringAOP 和 SpringMVC]

代理模式的分类 :

  • 静态代理
  • 动态代理

Imgur

10.1 静态代理

角色分析 :

  • 抽象角色 : 共同完成的事情(租房) , 一般会用接口或者抽象类来解决
  • 真实角色 : 被代理的角色(房东)
  • 代理角色 : 代理真实角色(中介) , 代理真实角色后,我们一般会做一些附属操作
  • 客户 : 访问代理对象的人(你)

Imgur

代码步骤 :

  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() {
            landlord.rent();
        }
    
        //看房
        public void seeHouse() {
            System.out.println("中介带你看房");
        }
    
        //收中介费
        public void fare() {
            System.out.println("收中介费");
        }
    
        //签合同
        public void hetong() {
            System.out.println("签租赁合同");
        }
    }
    
  4. 客户端访问代理角色

    public class Client {
        public static void main(String[] args) {
            //房东要租房子
            Proxy proxy = new Proxy(new Landlord());
            //代理,中介帮房东租房子,但是代理一般会有一些附属操作!
            proxy.hetong();
            proxy.fare();
            proxy.seeHouse();
    
            //你不用面对房东,直接找中介租房即可!
            proxy.rent();
        }
    }
    

代理模式和好处 :

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

缺点 :

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

10.2 加深理解

代码 : 1.以业务层添加日志为例子 :

Imgur

  1. 增删改查接口 :

Imgur

  1. 业务层实现

Imgur

  1. 添加一个代理类,并增加一个日志方法,这样可以不改动原有代码 .

Imgur

  1. 测试 :

横向开发导图 :

Imgur

10.3 动态代理

  • 动态代理和静态代理一样
  • 动态代理是动态生成的,不是我们写好的
  • 动态代理可分为两大类 : 基于接口的动态代理 , 基于类的动态代理
    • 基于接口 : JDK 动态代理 [例子中使用这个]
    • 基于类 : cglib
    • java字节码实现 : JAVAssist

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

  • Proxy提供了创建动态代理类的静态方法
  • InvocationHandler 是由代理实例的湖用处理程实现的接口。
    每个代理实例都有一个关联的调用处理程序。当在代理实例上调用方法时,方法调用将被编码并分派到其调用处理程序的invoke方法。

动态代理代码总览 :

Imgur

动态代理的核心 --->工具类: ProxyInvocationHandler.java

//等下我们会用这个类,自动生成代理类!
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 {
        //动态代理的本质,就是使用反射机制实现
        log(method.getName());
        return method.invoke(target, args);
    }

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

10.4 自己的理解

静态代理模式代码思路 :

接口 ---> 接口实现类 ---> 代理类 ---> 测试类

  • 接口中写要实现的方法

  • 接口实现类的作用十分纯粹 , 就是实现接口中的方法

  • 在代理类中将接口实现类作为一个私有属性,并通过set方法传参,实现代理

    private UserServiceImpl userService;
    
    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
    
  • 在测试类中new出代理类,代理类通过set方法,将new出来的接口实现类对象作为参数传参,就可以开始调用方法了

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

动态代理模式实现思路 :

  • 重点部分就是将将接口实现类作为一个私有属性,并通过set方法传参 , 动态代理将这个set方法传的具体参数类变为了一个可变的参数类. Object target代表一个未知的参数类(接口实现类).
//被代理的接口
private Object target;

public void setTarget(Object target) {
    this.target = target;
}
  • 既然这个参数类未知,那么我就得将它生成出来,通过反射来实现

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

    这是方法是一个固定写法,三个参数分别为:
    1.得到类加载器 2.得到代理的类的接口 3. this代表InvocationHandler .
    因为动态代理的工具类需要实现InvocationHandler接口,所以直接写 this

  • 现在已经通过反射获取了代理的接口,剩下的就是一个执行方法

    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质,就是使用反射机制实现
        return method.invoke(target, args);
    }
    

    这是继承InvocationHandler接口所需要实现的方法, 它的作用就是通过反射自动运行接口方法(它的实现是通过反射找到接口的接口实现类,并运行接口实现类的方法).

  • 如果要拓展方法就可以直接在工具类中加.

动态代理的完整工具类 :

//等下我们会用这个类,自动生成代理类!
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 {
        //动态代理的本质,就是使用反射机制实现
        log(method.getName());
        return method.invoke(target, args);
    }

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

测试类:

public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //被代理角色,不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        pih.setTarget(userService); //设置要代理的对象
        
        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();

        proxy.add();
        proxy.delete();
        proxy.update();
        proxy.query();
    }
}

简化一下:

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

        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        proxyInvocationHandler.setTarget(new UserServiceImpl());
        UserService proxy = (UserService) proxyInvocationHandler.getProxy();
        
        proxy.add();
        proxy.delete();
        proxy.update();
        proxy.query();
    }
}

实例化真实角色(接口实现类) ---> 实例化接口实现类 ---> 用接口实现类的set方法注入(代理)真实角色 ---> 用接口实现类的getProxy方法生成代理类 ---> 运行代理类的方法和拓展方法

11. AOP

11.1 什么是AOP

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

image-20200618134851969

11.2 AOP在Spring中的作用

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

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

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

11.3 使用Spring实现AOP

maven : AOP织入依赖包

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

xml配置 : (输入<aop:config>就可以alt+enter自动导入)

image-20200618151859100

以添加日志为例 :

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

前置日志 :

//method: 要执行的目标对象
//args: 参数
//target: 目标对象
public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        assert target != null;
        System.out.println(target.getClass().getName() + "的" + method.getName() + "被执行了");
    }
}

后置日志:

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);
    }
}

ApplicationContext.xml :

<!--注册bean-->
<bean id="userService" class="com.tan.service.UserServiceImpl"/>
<bean id="log" class="com.tan.log.Log"/>
<bean id="afterLog" class="com.tan.log.AfterLog"/>

<!--方式一: 使用原生Spring API接口-->
<!--配置aop-->
<aop:config>
    <!--切入点:-->
    <aop:pointcut id="pointcut" expression="execution(* com.tan.service.UserServiceImpl.*(..))"/>

    <!--执行环绕增加-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

</aop:config>

测试类:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");

        //UserServiceImpl userService = (UserServiceImpl) context.getBean("UserService"); 此写法报错,因为动态代理代理的是接口

        userService.add();

    }
}

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

diy日志类 :

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

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

ApplicationContext.xml :

<!--方式二: 自定义类-->
<bean id="diy" class="com.tan.diy.DiyPointCut"/>
<aop:config>
    <!--自定义切面, ref 要引用的类-->
    <aop:aspect ref="diy">

        <!--切入点-->
        <aop:pointcut id="point" expression="execution(* com.tan.service.UserServiceImpl .*(..))"/>
        <!--通知-->
        <aop:before method="before" pointcut-ref="point"/>
        <aop:after method="after" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>

方式三 : 使用注解实现

自定义注解类:

//方法三: 使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

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

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

    //在环绕增强中,我们给定一个参数,代表我们要获取切入的点
    @Around("execution(* com.tan.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {

        System.out.println("环绕前");
        jp.proceed();     //执行方法
        System.out.println("环绕后");

        Signature signature = jp.getSignature();
        System.out.println("执行的方法: "+signature);

    }

}

输出: 
环绕前
=========方法执行前==========
增加了一个用户.
环绕后
执行的方法: void com.tan.service.UserService.add()
=========方法执行后==========

ApplicationContext.xml :

<!--方式三: 注解实现-->
<bean id="annotationPointCut" class="com.tan.diy.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>

11.3.1 pointcut中的execution表达式

execution(\* com.sample.service.impl..\*.\*(..))

符号 含义
execution() 表达式的主体;
第一个”*“符号 表示返回值的类型任意;
com.sample.service.impl AOP所切的服务的包名,即,我们的业务部分
包名后面的”..“ 表示当前包及子包
第二个”*“ 表示类名,即所有类。此处可以自定义,下文有举例
.*(..) 表示任何方法名,括号表示参数,两个点表示任何参数类型

execution(* com.tan.service.UserServiceImpl.*(..))

返回所有参数,调用com.tan.service.UserServiceImpl下的所有方法,返回任何类型的参数

12. 整合Mybatis

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库(mysql-connector-java)
    • spring相关 (spring-webmvc , spring-jdbc )
    • aop织入(aspectjweaver)
    • mybatis-spring [new]
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--Spring操作数据库还需要spring-jdbc的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
    </dependencies>
    
  2. 编写配置文件

  3. 测试

12.1 回忆Mybatis

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

12.2 Mybatis-spring

mybatis-config.xml中的配置都转换成applicationContext.xml中的bean配置

虽然说spring配置文件可以将mybatis所有配置都转换过来,不过还是会留下一点mybatis配置(不然就一点面子都没了)

<?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核心配置环境-->
<configuration>

    <!--保留别名-->
    <typeAliases>
        <package name="com.tan.pojo"/>
    </typeAliases>

<!--    &lt;!&ndash;保留设置&ndash;&gt;-->
<!--    <settings>-->
<!--        <setting name="" value=""/>-->
<!--    </settings>-->

</configuration>

一般会选择保留别名和设置.

applicationContext.xml :

  1. 编写数据源

    <!--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.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    
  2. sqlSessionFactory

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--绑定Mapper.xml-->
        <property name="mapperLocations" value="classpath:com/tan/mapper/*.xml"/>
    </bean>
    
  3. sqlSessionTemplate

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

    接口 :

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

    接口加实现类 :

    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();
        }
    }
    
  5. 将自己写的实现类 , 注入到Spring中

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

    public class MyTest {
    
        @Test
        public void test() {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    
            for (User user : userMapper.selectUser()) {
                System.out.println(user);
            }
        }
    }
    

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

    <!--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.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

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

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


    <bean id="userMapper" class="com.tan.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>


</beans>

13. 声明式事务

1. 回顾事务

  • 把要么都成功,要么都失败
  • 事务在项目中十分的重要,涉及到事物的一致性,不能马虎
  • 确保完整性和一致性

事务ACID原则 :

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

2. spring中事务管理

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

使用事务applicationContext.xml中添加的东西 :

基本是固定写法.

<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource"/>
</bean>

<!--结合AOP实现事务的织入-->
<!--配置事务的类-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

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

propagation表示使用哪种事务的实现方式,一共有七种,但基本使用默认的,可以不写.

实现类:

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {

    public List<User> selectUser() {

        User user = new User(5, "tanshishi", "5465465441");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);

        mapper.addUser(user);
        mapper.deleteUser(6);


        return mapper.selectUser();
    }

    public void addUser(User user) {
        getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

测试时增和删要么都成功要么都失败

思考:

为什么需要事务?

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

重点部分 :

image-20200621170222861

撒花吗?算了算了......笔记越到后面越混......

下一个SpringMVC

猜你喜欢

转载自www.cnblogs.com/tanshishi/p/13125168.html