spring5学习笔记

1、Spring5入门

1.1 下载Spring5

下载地址:https://repo.spring.io/release/org/springframework/spring/

jar包下载地址:https://mvnrepository.com/

1.2 创建java项目

创建java项目时需要的5个基础的jar包:beans,context,core,expression和一个日志包。

1.3 新建一个User类

package com.danewang.spring5;

public class User {
    public void add(){
        System.out.println("add....");
    }
}

1.4 创建Spring配置文件,在配置文件配置创建对象

创建bean1.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--配置User对象创建-->
    <bean id="user" class="com.danewang.spring5.User"></bean>
</beans>

1.5 创建测试类

创建TestAdd.java测试类

package com.danewang.spring5.test;

import com.danewang.spring5.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class TestAdd {

    @Test
    public void testAdd() {
        //1.加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2.获取配置创建对象
        User user = context.getBean("user", User.class);
        System.out.println(user);
        user.add();
    }
}

1.6 运行测试类

2、IOC容器

本节包含4方面内容:

  1. IOC底层原理
  2. IOC接口(BeanFactory)
  3. IOC操作Bean管理(基于xml)
  4. IOC操作Bean管理(基于注解)
IOC(概念和原理)
  1. 什么是IOC

    1.1 控制反转,把对象创建和对象之间的调用过程,交给Spring处理

    1.2 使用IOC目的:为了耦合度降低

    1.3 做入门案例就是IOC实现

  2. IOC底层原理

    2.1 xml解析、工厂模式、反射

  3. 画图讲解IOC底层原理

    工厂模式:
    在这里插入图片描述

    IOC解耦:

在这里插入图片描述

IOC(接口)
  1. IOC思想基于IOC容器完成,IOC容器底层就是对象工厂

  2. Spring提供IOC容器实现两种方式:(两个接口)

    2.1 BeanFactory:IOC容器基本实现,是Spring内部使用接口,不提供开发人员使用

    加载配置文件时,不会创建对象,在获取对象或使用对象才去创建对象

    2.2 ApplicationContext:BeanFactory接口的子接口,提供更多更强大得到功能,一般由开发人员进行使用

    加载配置文件时候就会把在配置文件中的对象进行创建

  3. ApplicationContext接口有实现类

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5yYOh50m-1593094730498)(C:\Users\wwddd\AppData\Roaming\Typora\typora-user-images\image-20200624170940667.png)]

IOC操作 Bean管理(概念)
  1. 什么是Bean管理

    Bean管理指的是创建对象和注入属性

  2. Bean管理操作有两种方式

    2.1 基于xml配置文件方式实现

    2.2 基于注解方式实现

IOC操作 Bean管理(基于xml配置文件方式)
  1. 基于xml创建对象

        <!--配置User对象创建-->
        <bean id="user" class="com.danewang.spring5.User"></bean>
    

    1.1 在spring配置文件中,使用bean标签,标签里添加对应属性,就可以实现对象创建

    1.2 在bean标签有很多属性,介绍常用属性

    id属性:唯一标识

    class属性:类全路径(包类路径)

    1.3 在创建对象时,默认执行无参数构造方法完成对象创建

  2. 基于xml方式注入属性

    2.1 DI:依赖注入,就是注入属性

    第一种注入方式:使用set方法注入

    (1)创建类,定义属性和对应的set方法

    package com.danewang.spring5;
    
    /**
     * 演示使用set方法注入属性
     */
    public class Book {
        private String bname;
        private String bauthor;
    
        public void setBname(String bname) {
            this.bname = bname;
        }
    
        public void setBauthor(String bauthor) {
            this.bauthor = bauthor;
        }
    }
    

    (2)在spring配置文件配置对象创建,配置属性注入

        <!--set方法注入属性-->
        <bean id="book" class="com.danewang.spring5.Book">
            <!--使用property完成属性注入-->
            <property name="bname" value="张宇考研数学30讲"/>
            <property name="bauthor" value="张宇"/>
    
        </bean>
    

    (3)在测试类进行测试

        @Test
        public void testBook1() {
            //1.加载spring配置文件
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
            //2.获取配置创建对象
            Book book = context.getBean("book", Book.class);
            System.out.println(book);
            book.testDemo();
        }
    
    第二种注入方式:使用有参构造注入

    (1)创建类,定义属性,创建属性对应有参数构造方法

    package com.danewang.spring5;
    
    /**
     * 使用有参数构造方法
     */
    public class Orders {
        //属性
        private String oname;
        private String oaddress;
    
        //有参数构造方法
        public Orders(String oname, String oaddress) {
            this.oname = oname;
            this.oaddress = oaddress;
        }
    }
    

    (2)在spring配置文件进行配置

        <!--有参构造注入属性-->
        <bean id="orsers" class="com.danewang.spring5.Orders">
            <constructor-arg name="oname" value="电脑"/>
            <constructor-arg name="oaddress" value="nuc"/>
        </bean>
    
    p名称空间注入(了解)

    (1)使用p名称空间注入,可以简化基于xml配置方式

    ​ 第一步,添加p名称空间在配置文件中

    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    

    ​ 第二步,进行属性注入,在bean标签里面进行操作

        <bean id="book" class="com.danewang.spring5.Book" p:bname="西游记"/>
    
    IOC操作 Bean管理(xml注入其他类型属性)
    1. 字面量

      1.1 null值

              <property name="baddress">
                  <null></null>
              </property>
      

      1.2 属性包含特殊符号

              <!--设置特殊符号
                  1. 对<>进行转义,使用&lt;&gt
                  2. 把特殊符号内容写到CDATA
              -->
              <property name="baddress">
                  <value><![CDATA[<<南京>>]]></value>
              </property>
      
    2. 注入属性-外部Bean

      2.1 创建两个类service类和dao类

      2.2 在service调用dao里面的方法

      2.3 在spring配置文件中进行配置

      package com.danewang.spring5.service;
      
      import com.danewang.spring5.dao.UserDao;
      
      public class UserService {
      
          private UserDao userDao;
      
          public void setUserDao(UserDao userDao) {
              this.userDao = userDao;
          }
      
          public void add() {
              System.out.println("add...........");
          }
      }
      
      package com.danewang.spring5.dao;
      
      public class UserDaoImpl implements UserDao{
          @Override
          public void update() {
              System.out.println("dao update...........");
          }
      }
      
          <!--service和dao对象创建-->
          <bean id="userService" class="com.danewang.spring5.service.UserService">
              <!--注入userDao对象
                  name:类里面属性名称
                  ref:创建userDao对象bean标签id值
              -->
              <property name="userDaoImpl" ref="userDaoImpl"/>
          </bean>
          <bean id="userDaoImpl" class="com.danewang.spring5.dao.UserDaoImpl"/>
      
    3. 注入属性-内部Bean和级联赋值

      2.1第一种写法

      一对多关系:部门和员工

      一个部门有多个员工,一个员工属于一个部门

      部门是一,员工是多

      package com.danewang.spring5.bean;
      
      public class Dept {
          private String dname;
      
          public void setDname(String dname) {
              this.dname = dname;
          }
      
          @Override
          public String toString() {
              return dname;
          }
      }
      
      package com.danewang.spring5.bean;
      
      public class Emp {
          private String ename;
          private String egender;
          private Dept dept;
      
          public void setEname(String ename) {
              this.ename = ename;
          }
      
          public void setEgender(String egender) {
              this.egender = egender;
          }
      
          public void setDept(Dept dept) {
              this.dept = dept;
          }
      
          public void add() {
              System.out.println(ename + ": " + egender + ": " + dept.toString());
          }
      }
      
          <!--内部bean-->
          <bean id="emp" class="com.danewang.spring5.bean.Emp">
              <property name="ename" value="张三"/>
              <property name="egender" value=""/>
              <!--设置对象类的属性-->
              <property name="dept">
                  <bean id="dept" class="com.danewang.spring5.bean.Dept">
                      <property name="dname" value="安保部"/>
                  </bean>
              </property>
          </bean>
      
    4. 注入属性-级联赋值

      	//需要给Emp类加入getDept方法
      	public Dept getDept() {
              return dept;
          }
      
          <!--级联赋值-->
          <bean id="emp" class="com.danewang.spring5.bean.Emp">
              <property name="ename" value="张三"/>
              <property name="egender" value=""/>
              <property name="dept" ref="dept"/>
              <property name="dept.dname" value="管理部"/>
      
          </bean>
      
          <bean id="dept" class="com.danewang.spring5.bean.Dept">
              <property name="dname" value="技术部"/>
          </bean>
      
    IOC操作 Bean管理(xml注入集合属性)
    1. 注入数组类型属性
    2. 注入List集合类型属性
    3. 注入Map集合类型属性

    (1)创建类,定义数组、list、map、set类型属性的set方法

    package com.danewang.spring5.collectiontype;
    
    import java.util.List;
    import java.util.Map;
    
    public class Stu {
        //数组类型
        private String[] courses;
    
        //list集合类型
        private List<String> list;
    
        //map集合类型属性
        private Map<String, String> maps;
    
        public void setCourses(String[] courses) {
            this.courses = courses;
        }
    
        public void setList(List<String> list) {
            this.list = list;
        }
    
        public void setMaps(Map<String, String> maps) {
            this.maps = maps;
        }
    }
    

    (2)在spring配置文件进行配置

        <!--集合类型属性注入-->
        <bean id="stu" class="com.danewang.spring5.collectiontype.Stu">
            <!--数组类型属性注入-->
            <property name="courses">
                <array>
                    <value>java课程</value>
                    <value>数据库课程</value>
                </array>
            </property>
    
            <!--List类型属性注入-->
            <property name="list">
                <list>
                    <value>张三</value>
                    <value>法外狂徒</value>
                </list>
            </property>
    
            <!--Map类型属性注入-->
            <property name="maps">
                <map>
                    <entry key="JAVA" value="java"></entry>
                    <entry key="PHP" value="php"></entry>
                </map>
            </property>
    
            <!--Set类型属性注入-->
            <property name="sets">
                <set>
                    <value>MySQL</value>
                    <value>Redis</value>
                </set>
            </property>
        </bean>
    
    1. 在集合里面设置对象类型的值

          <!--创建多个course对象-->
          <bean id="course1" class="com.danewang.spring5.collectiontype.Course">
              <property name="cname" value="spring5"></property>
          </bean>
      
          <bean id="course2" class="com.danewang.spring5.collectiontype.Course">
              <property name="cname" value="spring4"></property>
          </bean>
      
              <!--注入List集合类型,值是对象-->
              <property name="courseList">
                  <list>
                      <ref bean="course1"></ref>
                      <ref bean="course2"></ref>
                  </list>
              </property>
      
    2. 把集合注入部分提取出来

      (1)在spring配置文件中引入名称空间util

      <?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:util="http://www.springframework.org/schema/util"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                                 http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util.xsd">
      

      (2)使用util标签完成list集合注入提取

          <!--提取list集合类型属性注入-->
          <util:list id="bookList">
              <value>易筋经</value>
              <value>九阴真经</value>
              <value>九阳神功</value>
          </util:list>
      
          <!--提取list集合类型属性注入使用-->
          <bean id="book" class="com.danewang.spring5.collectiontype.Book">
              <property name="list" ref="bookList"></property>
          </bean>
      
    IOC操作 Bean管理(FactoryBean)
    1. Spring有两种类型Bean,一种普通bean,另一种工厂bean(Factorybean)

    2. 普通bean:在配置文件中定义bean类型就是返回类型

    3. 工厂bean:在配置文件中定义bean类型可以和返回类型不一样

      3.1 创建类,让这个类作为工厂bean,实现接口FactoryBean

      3.2 实现接口里面的方法,在实现的方法中定义返回bean类型

      public class MyBean implements FactoryBean<Course> {
      
          //定义返回bean
          @Override
          public Course getObject() throws Exception {
              Course course=new Course();
              course.setCname("abc");
              return course;
          }
      
          @Override
          public Class<?> getObjectType() {
              return null;
          }
      
          @Override
          public boolean isSingleton() {
              return false;
          }
      }
      
          @Test
          public void test3() {
              ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean3.xml");
              Course course = applicationContext.getBean("myBean", Course.class);
              System.out.println(course);
          }
      
          <bean id="myBean" class="com.danewang.spring5.factorybean.MyBean">
          </bean>
      
    IOC操作 Bean管理(Bean作用域)
    1. 在spring里面,设置创建bean实例是单实例还是多实例

    2. 在spring里面,默认情况下,bean是单实例对象

    3. 如何设置单实例还是多实例

      3.1 在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例

      3.2 scope属性值

      第一个值 默认值:singleton,表示是单实例对象

      第二个值 prototype,表示是多实例对象

          <bean id="book" class="com.danewang.spring5.collectiontype.Book" scope="prototype">
              <property name="list" ref="bookList"></property>
      

      3.3 singleton和prototype区别

      (1)singleton单实例,prototype多实例

      (2)设置scope值是singleton的时候,加载spring配置文件就会创建单实例对象

      ​ 设置scope值是prototype的时候,不是在加载spring配置文件的时候创建对象,在调用getBean方法的时候创建多实例对象

    IOC操作 Bean管理(bean生命周期)
    1. 生命周期:从对象创建到对象销毁

    2. bean生命周期

      2.1 通过构造器创建bean实例(无参构造)

      2.2 为bean的属性设置值和对其他bean的引用(调用set方法)

      2.3 调用bean的初始化方法(需要进行配置初始化方法)

      2.4 bean可以使用了(对象获取到了)

      2.5 当容器关闭时候,调用bean销毁的方法(需要进行配置销毁的方法)

    3. 演示bean生命周期

      public class Orders {
      
          private String oname;
      
          public void setOname(String oname) {
              this.oname = oname;
              System.out.println("第二步 调用set方法设置属性值");
          }
      
          public Orders() {
              System.out.println("第一步 执行无参构造创建bean实例");
          }
      
          //创建执行的初始化方法
          public void initMethod() {
              System.out.println("第三步 执行初始化的方法");
          }
      
          //创建执行的销毁方法
          public void destroyMethod() {
              System.out.println("第五步 执行销毁的方法");
          }
      }
      
          <bean id="orders" class="com.danewang.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
              <property name="oname" value="手机"/>
          </bean>
      
          @Test
          public void test4() {
              //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean4.xml");
              ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean4.xml");
              Orders orders = applicationContext.getBean("orders", Orders.class);
              System.out.println("第四步 获取创建bean实例对象");
              System.out.println(orders);
              //手动让bean销毁
              applicationContext.close();
          }
      
    4. bean的后置处理器,bean的生命周期有七步

      4.1 通过构造器创建bean实例(无参构造)

      4.2 为bean的属性设置值和对其他bean的引用(调用set方法)

      4.3 把bean的实例传递bean后置处理器的方法:postProcessBeforeInitialization

      4.4 调用bean的初始化方法(需要进行配置初始化方法)

      4.5 把bean的实例传递bean后置处理器的方法:postProcessAfterInitialization

      4.6 bean可以使用了(对象获取到了)

      4.7 当容器关闭时候,调用bean销毁的方法(需要进行配置销毁的方法)

    5. 演示添加后置处理器效果

      5.1 创建类,实现接口BeanPostProcessor,创建后置处理器

      public class MyBeanPost implements BeanPostProcessor {
          @Override
          public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
              System.out.println("在初始化之前执行的方法");
              return bean;
          }
      
          @Override
          public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
              System.out.println("在初始化之后执行的方法");
              return bean;
          }
      
      }
      

      5.2 在spring配置文件配置后置处理器(默认为所有bean添加后置处理器)

          <bean id="orders" class="com.danewang.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
              <property name="oname" value="手机"/>
          </bean>
      
          <!--配置后置处理器-->
          <bean id="myBeanPost" class="com.danewang.spring5.bean.MyBeanPost">			</bean>
      
    IOC操作 Bean管理(xml自动装配)
    1. 什么是自动装配

      根据指定装配规则(属性名称或者属性类型),spring自动将匹配值进行注入

    2. 演示自动装配过程

      2.1 根据属性名称进行注入

          <!--实现自动装配
              bean标签属性autowire,配置自动装配
              autowire属性常用两个值:
                  byName:根据属性名称进行注入,注入值bean的id值和类属性名称一样
                  byType:根据属性类型进行注入-->
          <bean id="emp" class="com.danewang.spring5.autowire.Emp" autowire="byName"/>
          <bean id="dept" class="com.danewang.spring5.autowire.Dept"/>
      

      2.2 根据属性类型进行注入

          <!--实现自动装配
              bean标签属性autowire,配置自动装配
              autowire属性常用两个值:
                  byName:根据属性名称进行注入,注入值bean的id值和类属性名称一样
                  byType:根据属性类型进行注入-->
          <bean id="emp" class="com.danewang.spring5.autowire.Emp" autowire="byType"/>
          <bean id="dept" class="com.danewang.spring5.autowire.Dept"/>
      
    IOC操作 Bean管理(外部属性文件)
    1. 直接配置数据库信息

      1.1 配置德鲁伊连接池

      1.2 引入德鲁伊连接池依赖jar包

      druid-1.1.12.jar

          <!--直接配置连接池-->
          <bean id="dataSource" class="com.alibaba.druid.DruidDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/userDb"/>
              <property name="username" value="root"/>
              <property name="password" value="111111"/>
          </bean>
      
    2. 引入外部属性文件配置数据库连接池

      2.1 创建外部属性文件,properties格式文件,写数据库信息

      创建jdbc.properties

      prop.driverClass=com.mysql.jdbc.Driver
      prop.url=jdbc:mysql://localhost:3306/userDb
      prop.userName=root
      prop.password=111111
      

      2.2 把外部properties属性文件引入到spring配置文件中

      引入context名称空间

      <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:util="http://www.springframework.org/schema/util"
             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/util  http://www.springframework.org/schema/util/spring-util.xsd
                                 http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd">
      

      在 spring 配置文件使用标签引入外部属性文件

          <!--配置连接池-->
          <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
              <property name="driverClassName" value="${prop.driverClass}"/>
              <property name="url" value="${prop.url}"/>
              <property name="username" value="${prop.userName}"/>
              <property name="password" value="${prop.password}"/>
          </bean>
      
IOC操作 Bean管理(基于注解方式)
  1. 什么是注解

    1.1 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)

    1.2 使用注解,注解作用在类、方法、属性上面

    1.3 使用注解目的:简化xml配置

  2. Spring针对Bean管理中创建对象提供注解

    1. @Compotent

    2. @Service

    3. @Controller

    4. @Repository

      上面四个注解功能是一样的,都可以用来创建bean实例

  3. 基于注解方式实现对象创建

    1. 引入依赖

      spring-aop-5.2.7.RELEASE.jar

    2. 开启组件扫描

          <!--开启组件扫描
                  1. 如果扫描多个包,多个包用逗号隔开
                  2. 扫描包的上层目录-->
          <context:component-scan base-package="com.danewang.spring5.testdemo"></context:component-scan>
      
    3. 演示

      //在注解中,value可以省略,默认值是类名称的首字母小写
      //UserService-->userService
      @Component(value = "userService")
      public class UserService {
      
          public void add() {
              System.out.println("service add...");
          }
      }
      
          <!--开启组件扫描
                  1. 如果扫描多个包,多个包用逗号隔开
                  2. 扫描包的上层目录-->
          <context:component-scan base-package="com"></context:component-scan>
      
  4. 开启组件扫描细节配置

        <!--示例1:
                use-default-filters="false"表示不适用默认filter,自己配置filter
                context:include-filter,设置扫描哪些内容-->
        <context:component-scan base-package="com" use-default-filters="false">
            <context:include-filter type="annotation" expression="com.danewang.spring5.service"/>
        </context:component-scan>
    
        <!--示例2:
                下面配置扫描包所有内容
                context:exclude-filter:设置不扫描哪些内容-->
        <context:component-scan base-package="com">
            <context:exclude-filter type="annotation" expression="com.danewang.spring5.dao"/>
        </context:component-scan>
    
  5. 基于注解方式实现属性注入

    1. @AutoWired:根据属性类型进行自动装配

      1. 把service和dao对象创建,在service和dao类添加创建对象的注解
      2. 在service注入dao对象,在service类添加dao类属性,在属性上面使用注解
      @Service
      public class UserService {
      
          //定义dao类属性
          //不需要添加set方法
          //添加注入属性注解
          @Autowired
          private UserDao userDao;
      
          public void add() {
              System.out.println("service add...");
              userDao.add();
          }
      }
      
    2. @Qualifier:根据属性名称进行注入

      需要和@AutoWired一起使用

          //定义dao类属性
          //不需要添加set方法
          //添加注入属性注解
          @Autowired//根据类型进行注入
          @Qualifier(value = "userDaoImpl1")//根据名称进行注入
          private UserDao userDao;
      
    3. @Resource:可以根据类型注入,可以根据名称注入

          //@Resource//根据类型注入
          @Resource(name = "userDaoImpl1")
          private UserDao userDao;
      
    4. @Value:注入普通类型属性

          @Value(value = "abc")
          private String name;
      
  6. 完全注解开发

    1. 创建配置类,替代xml配置文件

      @Configuration//作为配置类,替代xml配置文件
      @ComponentScan(basePackages = {"com.danewang.spring5"})
      public class SpringConfig {
      }
      
    2. 编写测试类

          @Test
          public void testService2() {
              //加载配置类
              ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
              UserService userService = applicationContext.getBean("userService", UserService.class);
              System.out.println(userService);
              userService.add();
          }
      

3、AOP

AOP(概念)
  1. 什么是AOP

​ 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

  1. 通俗描述:不通过修改源代码方式,在主干功能里添加新功能
  2. 使用登录例子说明AOP
AOP(底层原理)
  1. AOP底层使用动态代理

    1. 有两种情况动态代理

      1. 有接口情况,使用JDK动态代理

        创建接口实现类的代理对象,增强类的方法

      2. 没有接口情况,使用CGLIB动态代理

    2. AOP(JDK动态代理)

      1. 使用JDK动态代理,使用Proxy类里面的方法创建代理对象

        Class Proxy

        static ObjectnewProxyInstance(ClassLoader loader, 类[] interfaces, InvocationHandler h)返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序。

        调用newProxyInstance方法

        ​ 方法有三个参数:

        ​ 第一个参数:类加载器

        ​ 第二个参数:增强方法所在的类,这个类实现的接口,支持多个接口

        ​ 第三个参数:实现这个接口InvocationHandler,创建代理对象,写增强方法

      2. 编写JDK动态代理代码

        1. 创建接口,定义方法

          public interface UserDao {
          
              public int add(int a, int b);
          
              public String update(String id);
          }
          
        2. 创建接口实现类,实现方法

          public class UserDaoImpl implements UserDao {
              @Override
              public int add(int a, int b) {
                  return a + b;
              }
          
              @Override
              public String update(String id) {
                  return id;
              }
          }
          
        3. 使用Proxy类创建接口代理对象

          public class JDKProxy {
          
              public static void main(String[] args) {
                  //创建接口实现类代理对象
                  Class[] interfaces = {UserDao.class};
          
                  UserDaoImpl userDao = new UserDaoImpl();
                  UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
                  int result = dao.add(1, 2);
                  System.out.println("result: " + result);
              }
          }
          
          
          //创建代理对象
          class UserDaoProxy implements InvocationHandler {
          
              //1. 把创建的是谁的代理对象,把谁传递过来
              //有参构造传递
              private Object obj;
          
              public UserDaoProxy(Object obj) {
                  this.obj = obj;
              }
          
              //增强的逻辑
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          
                  //方法之前
                  System.out.println("方法之前执行...." + method.getName() + "传递的参数:" + Arrays.toString(args));
          
                  //被增强的方法执行
                  Object invoke = method.invoke(obj, args);
          
                  //方法之后执行
                  System.out.println("方法之后执行...." + obj);
                  
                  return invoke;
              }
          }
          
AOP(术语)
  1. 连接点

    类里面哪些方法可以被增强,这些方法称为连接点

  2. 切入点

    实际被真正增强的方法,称为切入点

  3. 通知(增强)

    (1)实际增强的逻辑部分称为通知(增强)

    (2)通知有多种类型:

    前置通知

    后置通知

    环绕通知

    异常通知

    最终通知 :finally

  4. 切面

    是动作,把通知应用到切入点过程

AOP操作(准备)
  1. Spring框架一般基于AspectJ实现AOP操作

    1. 什么是AspectJ

      AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spring一起使用,进行AOP操作

  2. 基于AspectJ实现AOP操作

    1. 基于xml配置文件实现
    2. 基于注解方式实现(常用)
  3. 在项目工程中引入AOP相关依赖

  4. 切入点表达式

    1. 切入点表达式作用:知道对哪个类里面的哪个方法进行增强

    2. 语法结构:

      execution([权限修饰符] [返回类型] [类全路径] [方法名称] ([参数列表]) )

      举例1:对 com.danewang.spring5.BookDao 类里面的add进行增强

      execution(* com.danewang.spring5.BookDao.add(…))

      举例2:对 com.danewang.spring5.BookDao 类里面的所有方法进行增强

      execution(* com.danewang.spring5.BookDao.*(…))

      举例3:对 com.danewang.spring5 包里面的所有类,类里面的所有方法进行增强

(obj, args);

                //方法之后执行
                System.out.println("方法之后执行...." + obj);
                
                return invoke;
            }
        }
        ```
AOP(术语)
  1. 连接点

    类里面哪些方法可以被增强,这些方法称为连接点

  2. 切入点

    实际被真正增强的方法,称为切入点

  3. 通知(增强)

    (1)实际增强的逻辑部分称为通知(增强)

    (2)通知有多种类型:

    前置通知

    后置通知

    环绕通知

    异常通知

    最终通知 :finally

  4. 切面

    是动作,把通知应用到切入点过程

AOP操作(准备)
  1. Spring框架一般基于AspectJ实现AOP操作

    1. 什么是AspectJ

      AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spring一起使用,进行AOP操作

  2. 基于AspectJ实现AOP操作

    1. 基于xml配置文件实现
    2. 基于注解方式实现(常用)
  3. 在项目工程中引入AOP相关依赖

    [外链图片转存中…(img-SKUo3nMx-1593094730507)]

  4. 切入点表达式

    1. 切入点表达式作用:知道对哪个类里面的哪个方法进行增强

    2. 语法结构:

      execution([权限修饰符] [返回类型] [类全路径] [方法名称] ([参数列表]) )

      举例1:对 com.danewang.spring5.BookDao 类里面的add进行增强

      execution(* com.danewang.spring5.BookDao.add(…))

      举例2:对 com.danewang.spring5.BookDao 类里面的所有方法进行增强

      execution(* com.danewang.spring5.BookDao.*(…))

      举例3:对 com.danewang.spring5 包里面的所有类,类里面的所有方法进行增强

      execution(* com.danewang.spring5.*.*(…))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值