• 狂神说Spring学习笔记


    一、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!
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.2.0.RELEASEversion>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.2.0.RELEASEversion>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    1.2 优点

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

    1.3 组成

    在这里插入图片描述

    1.4 拓展

    现代化的Java开发!说白就是基于Spring的开发!

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

    因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
    弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”



    二、IOC理论推导

    1、UserDao 接口

    public interface UserDao {
        void getUser();
    }
    
    • 1
    • 2
    • 3

    2、UserDaoImpl 实现类

    public class UserDaoImpl implements UserDao {
        public void getUser() {
            System.out.println("默认获取用户数据");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3、UserService 业务接口

    public class UserServiceImpl implements UserService {
    
        private UserDao userDao = new UserDaoImpl();
    
        public void getUser() {
            userDao.getUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4、UserServiceImpl 业务实现类

    public class UserServiceImpl implements UserService {
    
        private UserDao userDao = new UserDaoImpl();
    
        public void getUser() {
            userDao.getUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    5、测试

    public class MyTest {
        public static void main(String[] args) {
    
            //用户实际调用的是业务层,dao层他们不需要接触!
            UserService userService = new UserServiceImpl();
            userService.getUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
    在这里插入图片描述
    我们使用一个Set接口实现,已经发生了革命性的变化!

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

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

    IOC本质

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

    采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
    控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。



    三、HelloWorld

    3.1、新建一个maven项目,编写实体类

    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 + '\'' +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3.2、编写xml配置文件

    
    <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="hello" class="com.kuang.pojo.Hello">
            <property name="str" value="只因"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3.3、测试

        public class MyTest {
        public static void main(String[] args) {
            //获取Spring的上下文对象!
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    
            //我们的对象现在都在Spring中的管理了,我们需要使用,直接去里面取出来就可以!
            Hello hello = (Hello) context.getBean("hello");
            System.out.println(hello.toString());  //Hello{str='只因'}
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    思考问题?

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

    这个过程就叫控制反转:
    控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。
    反转:程序本身不创建对象,而变成被动的接收对象。
    依赖注入:就是利用set方法来进行注入的。
    IOC是一种编程思想,由主动的编程变成被动的接收。
    可以通过new ClassPathXmlApplicationContext去浏览一下底层源码。
    OK,到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话搞定:对象由Spring来创建,管理,装配!


    四、IOC创建对象的方式

    4.1、使用无参构造创建对象,默认!

    4.2、使用有参构造创建对象

    4.2.1、下标赋值

    
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="狂神说Java"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4

    4.2.2、类型

    
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg type="java.lang.String" value="lifa"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4

    4.2.3、参数名

    
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="李发"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4

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


    五、Spring的配置

    5.1、别名

    
        <alias name="user" alias="userNew"/>
    
    • 1
    • 2

    5.2、Bean的配置

     
        <bean id="userT" class="com.kuang.pojo.UserT" name="user2 u2,u3;u4">
            <property name="name" value="黑心白莲"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    5.3、Import

    这个import。一般用于团队开发使用,它可以将多个配置文件,导入合并为一个。
    假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

    • 张三
    • 李四
    • 王五
    • applicationContext.xml
    <import resource="bean.xml"/>
    <import resource="bean2.xml"/>
    <import resource="bean3.xml"/>
    
    • 1
    • 2
    • 3

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



    六、依赖注入

    6.1 构造器注入

    前面已经介绍过,参考4、IOC创建对象的方式

    6.2 Set方式注入【重点】

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

    6.2.1、复杂类型

    public class Address {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.2.2、真实测试对象

    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 String wife;
        private Properties info;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.2.3、beans.xml

    
    <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.kuang.pojo.Student">
            
            <property name="name" value="黑心白莲"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.2.4、测试类

      <bean id="address" class="com.kuang.pojo.Address">
            <property name="address" value="西安"/>
        bean>
    
        <bean id="student" class="com.kuang.pojo.Student">
            
            <property name="name" value="黑心白莲"/>
    
            
            <property name="address" ref="address"/>
    
            
            <property name="books">
                <array>
                    <value>红楼梦value>
                    <value>西游记value>
                    <value>水浒传value>
                    <value>三国演义value>
                array>
            property>
    
            
            <property name="hobbies">
                <list>
                    <value>打篮球value>
                    <value>看电影value>
                    <value>敲代码value>
                list>
            property>
    
            
            <property name="card">
                <map>
                    <entry key="身份证" value="123456789987456321"/>
                    <entry key="银行卡" value="359419496419481649"/>
                map>
            property>
    
            
            <property name="games">
                <set>
                    <value>LOLvalue>
                    <value>COCvalue>
                    <value>BOBvalue>
                set>
            property>
    
            
            <property name="wife">
                <null/>
            property>
    
            
            <property name="info">
                <props>
                    <prop key="driver">20191029prop>
                    <prop key="url">102.0913.524.4585prop>
                    <prop key="user">黑心白莲prop>
                    <prop key="password">123456prop>
                props>
            property>
    
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    6.3、 拓展方式注入

    我们可以使用p命名空间和c命名空间进行注入
    官方解释:
    在这里插入图片描述

    使用:

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
        <bean id="user" class="com.kuang.pojo.User" p:name="黑心白莲" p:age="20"/>
    
        
        <bean id="user2" class="com.kuang.pojo.User" c:name="狂神" c:age="22"/>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    测试:

     @Test
        public void test2(){
            ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    
            User user = context.getBean("user",User.class);
            System.out.println(user);
    
            User user2 = context.getBean("user2",User.class);
            System.out.println(user2);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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

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

    6.4、bean的作用域

    在这里插入图片描述

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

    <bean id="user2" class="com.kuang.pojo.User" c:name="狂神" c:age="22" scope="singleton"/>
    
    • 1

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

    <bean id="user2" class="com.kuang.pojo.User" c:name="狂神" c:age="22" scope="prototype"/>
    
    • 1

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



    七、Bean的自动装配(2020-11-11)

    • 自动装配是Spring满足bean依赖一种方式!
    • Spring会在上下文中自动寻找,并自动给bean装配属性!
      在Spring中有三种装配的方式:
      1、在xml中显式的配置;
      2、在java中显式配置;
      3、隐式的自动装配bean【重要】

    7.1 测试

    环境搭建:创建项目,一个人有两个宠物!

        <bean id="cat" class="com.kuang.pojo.Cat"/>
        <bean id="dog" class="com.kuang.pojo.Dog"/>
    
        <bean id="people" class="com.kuang.pojo.People">
            <property name="name" value="小白莲"/>
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    7.2 ByName自动装配

    
            <bean id="people" class="com.kuang.pojo.People" autowire="byName">
                <property name="name" value="小白莲"/>
            bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    7.3 ByType自动装配

       
            <bean id="people" class="com.kuang.pojo.People" autowire="byType">
                <property name="name" value="小白莲"/>
            bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    小结:

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

    7.4 使用注解实现自动装配

    jdk1.5支持的注解,Spring2.5就支持注解了!
    要使用注解须知:
    1、导入约束
    2、配置注解的支持

    
    <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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    @Autowired
    直接在属性上使用即可!也可以在set方法上使用!
    使用Autowired我们就可以不用编写set方法了,前提是你这个自动配置的属性在IOC(Spring)容器中存在,且符合名字ByName!

    科普:

    @Nullable 字段标记了了这个注解,说明这个字段可以为null;
    
    • 1

    测试代码:

    public class People {
        //如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
        @Autowired(required = false)
        private Cat cat;
        @Autowired
        private Dog dog;
        private String name;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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

    public class People {
        @Autowired
        @Qualifier(value = "cat111")
        private Cat cat;
        @Autowired
        @Qualifier(value = "dog222")
        private Dog dog;
        private String name;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    @Resource

    public class People {
    
        @Resource
        private Cat cat;
    
        @Resource
        private Dog dog;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    小结:
    @Resource和@Autowired的区别:

    • 都是用来自动装配的,都可以放在属性字段上
    • @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
    • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
    • 执行顺序不同:@Autowired通过byType的方式实现。


    八、使用注解开发

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

    使用注解需要导入约束,配置注解的支持!

    
    <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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    1、bean
    2、属性如何注入

    //等价于
    //@Component 组件
    
    @Component
    public class User {
    
        //相当于  
        @Value("白莲")
        public String name;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    dao 【@Repository】
    service 【@Service】
    controller 【@Controller】
    
    • 1
    • 2
    • 3

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

    4、自动装配

    - @Autowired:自动装配通过类型,名字。如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = "xxx")去配置。
    - @Nullable 字段标记了了这个注解,说明这个字段可以为null;
    - @Resource:自动装配通过名字,类型。
    
    • 1
    • 2
    • 3

    5、作用域

    @Component
    @Scope("singleton")
    public class User {
    
        //相当于  
        @Value("白莲")
        public String name;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    6、小结
    xml与注解:
    xml更加万能,适用于任何场合!维护简单方便
    注解不是自己类使用不了,维护相队复杂!
    xml与注解最佳实践:
    xml用来管理bean;
    注解只负责完成属性的注入;
    我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

    
        <context:component-scan base-package="com.kuang"/>
        
        <context:annotation-config/>
    
    • 1
    • 2
    • 3
    • 4



    九、使用Java的方式配置Spring

    我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
    JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!

    实体类

    //这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
    @Component
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        @Value("黑心白莲") //属性注入值
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    配置文件

    // 这个也会Spring容器托管,注册到容器中,因为它本来就是一个@Component
    // @Configuration代表这是一个配置类,就和我们之前看的beans.xml
    @Configuration
    @ComponentScan("com.kuang.pojo")
    @Import(KuangConfig2.class)
    public class KuangConfig {
    
        // 注册一个bean,就相当于我们之前写的一个bean标签
        // 这个方法的名字,就相当于bean标签中id属性
        // 这个方法的返回值,就相当于bean标签中的class属性
        @Bean
        public User user(){
            return new User(); // 就是返回要注入到bean的对象!
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    测试类

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



    十、代理

    为什么要学习代理模式,因为AOP的底层机制就是动态代理!

    代理模式:

    • 静态代理

    • 动态代理

    学习aop之前 , 我们要先了解一下代理模式!
    在这里插入图片描述

    静态代理

    静态代理角色分析

    • 抽象角色 : 一般使用接口或者抽象类来实现

    • 真实角色 : 被代理的角色

    • 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .

    • 客户 : 使用代理角色来进行一些操作 .

    代码实现

    Rent . java 即抽象角色

    //抽象角色:租房
    public interface Rent {
        public void rent();
    }
    
    • 1
    • 2
    • 3
    • 4

    Host.java即真实角色

    //真实角色: 房东,房东要出租房子
    public class Host implements Rent{
        public void rent() {
            System.out.println("房屋出租");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Proxy . java 即代理角色

    //代理角色:中介
    public class Proxy implements Rent {
     
        private Host host;
        public Proxy() { }
        public Proxy(Host host) {
            this.host = host;
        }
     
        //租房
        public void rent(){
            seeHouse();
            host.rent();
            fare();
        }
        //看房
        public void seeHouse(){
            System.out.println("带房客看房");
        }
        //收中介费
        public void fare(){
            System.out.println("收中介费");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    Client.java即客户

    //客户类,一般客户都会去找代理!
    public class Client {
        public static void main(String[] args) {
            //房东要租房
            Host host = new Host();
            //中介帮助房东
            Proxy proxy = new Proxy(host);
     
            //你去找中介!
            proxy.rent();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    分析:在这个过程中,你直接接触的就是中介,就如同现实生活中的样子,你看不到房东,但是你依旧租到了房东的房子通过代理,这就是所谓的代理模式,程序源自于生活,所以学编程的人,一般能够更加抽象的看待生活中发生的事情。

    静态代理的好处:

    • 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .

    • 公共的业务由代理来完成 . 实现了业务的分工 ,

    • 公共业务发生扩展时变得更加集中和方便 .

    缺点 :

    • 类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 .

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

    静态代理再理解

    同学们练习完毕后,我们再来举一个例子,巩固大家的学习!

    练习步骤:

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

    //抽象角色:增删改查业务
    public interface UserService {
        void add();
        void delete();
        void update();
        void query();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2、我们需要一个真实对象来完成这些增删改查操作

    //真实对象,完成增删改查操作的人
    public class UserServiceImpl implements UserService {
     
        public void add() {
            System.out.println("增加了一个用户");
        }
     
        public void delete() {
            System.out.println("删除了一个用户");
        }
     
        public void update() {
            System.out.println("更新了一个用户");
        }
     
        public void query() {
            System.out.println("查询了一个用户");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3、需求来了,现在我们需要增加一个日志功能,怎么实现!

    • 思路1 :在实现类上增加代码 【麻烦!】

    • 思路2:使用代理来做,能够不改变原来的业务情况下,实现此功能就是最好的了!

    4、设置一个代理类来处理日志!代理角色

    //代理角色,在这里面增加日志的实现
    public class UserServiceProxy implements UserService {
        private UserServiceImpl userService;
     
        public void setUserService(UserServiceImpl userService) {
            this.userService = userService;
        }
     
        public void add() {
            log("add");
            userService.add();
        }
     
        public void delete() {
            log("delete");
            userService.delete();
        }
     
        public void update() {
            log("update");
            userService.update();
        }
     
        public void query() {
            log("query");
            userService.query();
        }
     
        public void log(String msg){
            System.out.println("执行了"+msg+"方法");
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    5、测试访问类:

    public class Client {
        public static void main(String[] args) {
            //真实业务
            UserServiceImpl userService = new UserServiceImpl();
            //代理类
            UserServiceProxy proxy = new UserServiceProxy();
            //使用代理类实现日志功能!
            proxy.setUserService(userService);
     
            proxy.add();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    OK,到了现在代理模式大家应该都没有什么问题了,重点大家需要理解其中的思想;

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

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

    动态代理

    动态代理的角色和静态代理的一样 .

    动态代理的代理类是动态生成的 . 静态代理的代理类是我们提前写好的

    动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理

    • 基于接口的动态代理----JDK动态代理

    • 基于类的动态代理–cglib

    • 现在用的比较多的是 javasist 来生成动态代理 . 百度一下javasist

    • 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!

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

    核心 : InvocationHandler和Proxy, 打开JDK帮助文档看看

    【InvocationHandler:调用处理程序】

    代码实现

    抽象角色和真实角色和之前的一样!

    Rent . java 即抽象角色

    //抽象角色:租房
    public interface Rent {
        public void rent();
    }
    
    • 1
    • 2
    • 3
    • 4

    Host . java 即真实角色

    //真实角色: 房东,房东要出租房子
    public class Host implements Rent{
        public void rent() {
            System.out.println("房屋出租");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ProxyInvocationHandler. java 即代理角色

    public class ProxyInvocationHandler implements InvocationHandler {
        private Rent rent;
     
        public void setRent(Rent rent) {
            this.rent = rent;
        }
     
        //生成代理类,重点是第二个参数,获取要代理的抽象角色!之前都是一个角色,现在可以代理一类角色
        public Object getProxy(){
            return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    rent.getClass().getInterfaces(),this);
        }
     
        // proxy : 代理类 method : 代理类的调用处理程序的方法对象.
        // 处理代理实例上的方法调用并返回结果
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            seeHouse();
            //核心:本质利用反射实现!
            Object result = method.invoke(rent, args);
            fare();
            return result;
        }
     
        //看房
        public void seeHouse(){
            System.out.println("带房客看房");
        }
        //收中介费
        public void fare(){
            System.out.println("收中介费");
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    Client . java

    //租客
    public class Client {
     
        public static void main(String[] args) {
            //真实角色
            Host host = new Host();
            //代理实例的调用处理程序
            ProxyInvocationHandler pih = new ProxyInvocationHandler();
            pih.setRent(host); //将真实角色放置进去!
            Rent proxy = (Rent)pih.getProxy(); //动态生成对应的代理类!
            proxy.rent();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    核心:一个动态代理 , 一般代理某一类业务 , 一个动态代理可以代理多个类,代理的是接口!
    在这里插入图片描述


    十一、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:
    在这里插入图片描述
    在这里插入图片描述

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

    11.3 使用Spring实现AOP

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

    
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.9.4version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    方式一: 使用Spring的API接口【主要是SpringAPI接口实现】
    1、在service包下,定义UserService业务接口和UserServiceImpl实现类

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void select();
    }
    
    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("查询了一个用户!");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2、在log包下,定义我们的增强类,一个Log前置增强和一个AfterLog后置增强类

    public class Log implements MethodBeforeAdvice {
    
        //method: 要执行的目标对象的方法
        //args:参数
        //target:目标对象
        public void before(Method method, Object[] agrs, Object target) throws Throwable {
            System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3、最后去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束,配置applicationContext.xml文件

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        
        <bean id="userService" class="com.kuang.service.UserServiceImpl"/>
        <bean id="log" class="com.kuang.log.Log"/>
        <bean id="afterLog" class="com.kuang.log.AfterLog"/>
    
        
        
        <aop:config>
            
            <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
    
            
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        aop:config>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    4、测试

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            //动态代理代理的是接口:注意点
            UserService userService = (UserService) context.getBean("userService");
    
            userService.add();
    //        userService.select();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    方式二: 自定义类来实现AOP【主要是切面定义】
    1、在diy包下定义自己的DiyPointCut切入类

    public class DiyPointCut {
        public void before(){
            System.out.println("======方法执行前======");
        }
    
        public void after(){
            System.out.println("======方法执行后======");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2、去spring中配置文件

        
        <bean id="diy" class="com.kuang.diy.DiyPointCut"/>
    
        <aop:config>
            
            <aop:aspect ref="diy">
                
                <aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
                
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
            aop:aspect>
        aop:config>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3、测试

    方式三: 使用注解实现!
    1、在diy包下定义注解实现的AnnotationPointCut增强类

    //声明式事务!
    @Aspect //标注这个类是一个切面
    public class AnnotationPointCut {
    
        @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("====方法执行前====");
        }
    
        @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("====方法执行后====");
        }
    
        //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
        @Around("execution(* com.kuang.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("环绕后");
    
            System.out.println(proceed);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    2、在Spring配置文件中,注册bean,并增加支持注解的配置。

        
        <bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
        
        <aop:aspectj-autoproxy/>
    
    • 1
    • 2
    • 3
    • 4

    3、测试

  • 相关阅读:
    MaTiJi - MT3143 - 试管装液
    图解|从根上彻底理解MySQL的索引
    微信小程序开发公司你懂得选择吗?
    [Mac软件]Adobe XD(Experience Design) v57.1.12.2一个功能强大的原型设计软件
    C语言 extern “C“的作用
    【云原生】FlexCloud 云数据转HTTP开发接口操作
    Vue项目实战——实现GitHub搜索案例(学以致用,两小时带你巩固和强化Vue知识点)
    软件开发模型
    T Chat 第八期「 龙熠 - 我在大厂做国际化 」8 月 18 日晚 8 点开播
    Spring Boot发送邮件
  • 原文地址:https://blog.csdn.net/G823909/article/details/128123697