Spring框架学习

1、Spring

1.1、简介

  • 2020年,首次退出了Spring框架的雏形:interface21框架

  • 2004年,Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,发布了Spring 1.0版

  • Spring理念:使现有的技术更加容易使用,本身是个大杂烩。整合了现有的技术框架

  • SSH:Strus2+Spring+Hibernate

  • SSM:SpringMVC+Spring+Mybatis

1.2、优点

  • Spring是一个开源的免费框架(容器)

  • Spring是一个轻量级的、非入侵式的框架

  • 控制反转(IOC),面向切面编程(AOP)

  • 支持事务的处理,对框架整合的支持

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

1.3、组成

image-20201129213412303

1.4、拓展

  • Spring Boot

    • 一个快速开发的脚手架

    • 基于SpringBoot可以快速的开发单个微服务

    • 约定大于配置

  • Spring Cloud

    • SpringCloud是基于SpringBoot实现的

大多数公司都在使用SpringBoot进行快速开发,但学习SpringBoot的前提需要完全掌握Spring及SpringMVC

 

2、IOC理论推导

  1. UserDao 接口

  2. UserDaoImpl 实现类

  3. UserService 业务接口

  4. UserServiceImpl 业务实现类

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

 

我们使用一个Set接口实现

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

 

  • 之前,程序主动创建对象

  • 使用set注入后,程序不再具有主动性,而是变成被动的接收对象

 

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

IOC本质

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

 

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,

Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

 

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

3、HelloSpring

3.1、实例

Pojo类

注:需要有set方法来进行依赖注入

 package com.sy.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 + '\'' +
                 '}';
    }
 }

beans.xml(spring容器)

一个bean是一个具体的对象,不再需要在代码中new对象,一切由spring托管

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--使用Spring来创建对象,在spring中这些都称为bean
         类型 变量名 = new 类型();
         Hello hello = new Hello();
 
 
         bean = 对象   new Hello();
         id = 变量名
         class = new 的对象:
         property 相当于给对象属性设值
     -->
     <bean id="hello" class="com.sy.pojo.Hello">
         <property name="str" value="Spring"></property>
     </bean>
 </beans>

测试类

 import com.sy.pojo.Hello;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 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对象是由谁创建的?

    hello对象是由Spring创建的

  • Hello对象的属性是怎样设置的?

    hello对象的属性是由Spring容器设置的

这个过程就叫控制反转:

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的

反转:程序本身不创建对象,而变成被动的接收对象。

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

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

可以通过newClassPathXmlApplicationContext去浏览底层源码

我们彻底不用再程序中去改动了,要实现不同的操作,只需要再xml配置文件中进行修改,所谓的IoC,一句话而言:对象由Spring来创建,管理,装配。

当Bean中对象需要与其他对象组合时

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd">
         <bean id="mysqlImpl" class="com.sy.dao.UserDaoMysqlImpl"/>
         <bean id="oracleImpl" class="com.sy.dao.UserDaoOracleImpl"/>
         <bean id="userServiceImpl" class="com.sy.service.UserServiceImpl">
             <!--ref:引用Spring容器中创建好的对象
                 value:具体的值,基本数据类型
             -->
             <property name="userDao" ref="oracleImpl"/>
         </bean>
 </beans>

4、IOC创建对象的方式

构造器注入


  1. 使用无参构造创建对象(默认)

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

    1. 下标赋值

       <bean id="user" class="com.sy.pojo.User">
           <property name="name" value="Shenyang"/>
           <constructor-arg index="0" value="沈洋"/>
       </bean>
    2. 类型赋值

       <!--    不建议使用-->
           <bean id="user" class="com.sy.pojo.User">
               <constructor-arg type="java.lang.String" value="沈洋"/>
           </bean>

    3.参数名

     <bean id="user" class="com.sy.pojo.User">
         <constructor-arg name="name" value="shenyang"/>
     </bean>

总结:在配置文件(beans.xml)加载时,容器中管理的对象就已经初始化了(spring会将所有的bean对象创建出来)

5. Spring配置

5.1、别名

<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="user2"/>

5.2、Bean的配置

 <!--
 id:bean的唯一标识符,也就是相当于我们学的对象名
 class:bean对象所对应的全限定名:包名 + 类名
 name: 也是别名,而且name可以同时取多个别名 name="user1,user2"
 -->
 <bean id="userT" name="user1,user4" class="com.sy.pojo.UserT">
     <property name="name" value="shenyang"/>
 </bean>

5.3、import

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

  • 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">
             <import resource="beans.xml"/>
             <import resource="beans2.xml"/>
             <import resource="beans3.xml"/>
     </beans>

6、依赖注入

6.1、构造器注入

第四节IOC创建对象

6.2、Set方式注入【重点】

  • 依赖注入:Set注入

    • 依赖:bean对象的创建依赖于容器

    • 注入:bean对象中的所有属性,由容器来注入

【环境搭建】

  1. 复杂类型

    package com.sy.pojo;
    
    public class Address {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
  2. 真实测试对象

     package com.sy.pojo;
     
     import java.util.*;
     
     public class Student {
         private Address address;
         private String name;
         private String[] book;
         private List<String > hobbys;
         private Map<String,String> card;
         private Set<String> games;
         private Properties info;
         private String wife;
     }
  3. beans.xml

     <bean id="student" class="com.sy.pojo.Student">
         <!--第一种,普通注入,value-->
         <property name="name" value="沈洋"/>
     </bean>
  4. 测试类

     import com.sy.pojo.Student;
     import org.springframework.context.ApplicationContext;
     import org.springframework.context.support.ClassPathXmlApplicationContext;
     
     public class MyTest {
         public static void main(String[] args) {
             ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
             Student student = (Student)context.getBean("student");
             System.out.println(student);
        }
     }

完善注入信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="address" class="com.sy.pojo.Address">
            <property name="address" value="四川成都"/>
        </bean>
        <bean id="student" class="com.sy.pojo.Student">
            <!--第一种,普通注入,value-->
            <property name="name" value="沈洋"/>
            <!--第二种,Bean注入,ref-->
            <property name="address" ref="address"/>
            <!--第三种,数组注入,array-->
            <property name="book">
                <array>
                    <value>红楼梦</value>
                    <value>西游记</value>
                    <value>水浒传</value>
                    <value>三国演义</value>
                </array>
            </property>
            <!--第四种,list注入,list-->
            <property name="hobbys">
                <list>
                    <value>听歌</value>
                    <value>敲代码</value>
                    <value>看电影</value>
                </list>
            </property>
            <!--Map-->
            <property name="card">
                <map>
                    <entry key="身份证" value="510521200008027896"/>
                    <entry key="银行卡" value="21312313213123"/>
                </map>
            </property>
            <!--set注入-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>COC</value>
                    <value>BOB</value>
                </set>
            </property>
            <!--null值注入-->
            <property name="wife">
                <null/>
            </property>
            <!--property注入-->
            <property name="info">
                <props>
                    <prop key="学号">2019110231</prop>
                    <prop key="性别">男</prop>
                    <prop key="姓名">沈洋</prop>
                </props>
            </property>
        </bean>
</beans>

6.3、拓展方式注入

我们可以使用p命名空间进行属性注入

也可以通过c命名空间进行构造注入

两种方式对应的就是构造器注入和set方式注入

<?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命名空间注入,可以直接注入属性的值-->
        <bean id="user" class="com.sy.pojo.User" p:age="18" p:name="沈洋"/>
<!--        c命名空间注入,通过构造器注入:-->
        <bean id="user2" class="com.sy.pojo.User" c:age="18" c:name="起飞"/>
</beans>

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

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

6.4、Bean的作用域

image-20201201145911558

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

    所有对象共享一个

    <bean id="user" class="com.sy.pojo.User" scope="singleton" p:age="18" p:name="沈洋"/>
  2. 原型模式:每次从容器中get时,都会产生一个新对象

     <bean id="user" class="com.sy.pojo.User" scope="prototype" p:age="18" p:name="沈洋"/>
  3. 其余 request、session、application,这些只能在web开发中使用到

7、Bean的自动装配

  • 自动装配

  • Spring会在上下文中自动寻找,并自动给bean装配属性

在Spring中有三种装配的方式

  1. 在xml中显示的装配

  2. 在java中显示配置

  3. 隐式的自动装配Bean【重要】

7.1、自动装配测试

  1. 环境搭建

    • 一个人有两个宠物

7.2、ByName自动装配

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd">
     <bean id="cat" class="com.sy.pojo.Cat">
         <property name="name" value="猫一"/>
     </bean>
     <bean id="dog" class="com.sy.pojo.Dog">
         <property name="name" value="狗一"/>
     </bean>
 
     <!--
         byName:会在容器上下文查找,和自己对象set方法后面的值对应的bean id
         byType:会在容器上下文查找,和自己对象类型相同的bean
     -->
     <bean id="people" class="com.sy.pojo.People" autowire="byName">
         <property name="name" value="沈洋"/>
     </bean>
 </beans>

注意:ByName自动装配是根据类中set方法的 变量名查找的

将上述bean中的cat改为cat1等,将出现装配失败

7.3、ByType自动装配

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.sy.pojo.Cat">
        <property name="name" value="猫一"/>
    </bean>
<!--    <bean id="cat2" class="com.sy.pojo.Cat">-->
<!--        <property name="name" value="猫二"/>-->
<!--    </bean>-->
    <bean id="dog" class="com.sy.pojo.Dog">
        <property name="name" value="狗一"/>
    </bean>

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

注意:byType是通过在bean中查找类型对应的bean进行自动装配的,当配置文件中出现两个相同类型的bean时,自动装配失败

 

小结

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

  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

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

一般情况下,注解优于xml配置

使用注解须知:

  1. 导入约束(Contetx约束)

     xmlns:context="http://www.springframework.org/schema/context"   
  2. 配置注解的支持 context:annotation-config/ 【重要】

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

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

科普:

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

测试代码

public class People {
    //如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否者不允许为空
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;
    private String name;
}

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

public class People {
    @Autowired
    @Qualifier(value = "dog22")
    private Dog dog;
    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;
    private String name;
}

 

@Resource注解

public class People {
    @Resource(name="cat2")
    private Dog dog;
    @Resource
    private Cat cat;
    private String name;
}

小结:

@Resource和@Autowired的区别

  • 都是用来自动装配的

  • 都可以放在属性字段上

  • @Autowired 通过byName的方式实现,对象必须存在

  • @Resource 默认通过byName的方式实现,如果找不到名字,则通过byType实现,如果找不到的情况下,就报错

 

8、使用注解开发

Spring 4之后,要使用注解开发,必须要保证aop的包导入

image-20201201170710482

使用注解需要导入context的约束,增加注解的支持

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

    <context:annotation-config/>

</beans>
  1. bean

  2. 属性如何注入

    package com.sy.dao;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    //等价于<bean id="user" class="com.sy.pojo.User">
    @Component
    public class User {
        //相当于在xml中使用
        @Value("shenyang")
        public String name;
        //相当于<property name="name" value="沈洋">
        @Value("沈洋")
        public void setName(String name) {
            this.name = name;
        }
    }
  3. 衍生的注解

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

    • dao【@Repository】

    • service【@Service】

    • controller【@Controller】

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

  4. 自动装配

  5. 作用域

    @Component
    @Scope("prototype")
    public class User {
    
        public String name;
        
        //相当于<property name="name" value="沈洋">
        @Value("沈洋")
        public void setName(String name) {
            this.name = name;
        }
    }
  6. 小结

    xml与注解:

    • xml更加万能,适用于任何场合,维护简单方便

    • 注解 不是自己的类使用不了,维护相对复杂

    xml与注解最佳实践:

    • xml用来管理bean

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

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

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

 

9、使用Java的方式配置Spring

不使用Spring的xml配置,全权交给Java

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

image-20201202200930158

实体类

 package com.sy.pojo;
 
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 @Component
 public class User {
 
     private String name;
 
     public String getName() {
         return name;
    }
     @Value("沈洋")
     public void setName(String name) {
         this.name = name;
    }
 
     @Override
     public String toString() {
         return "User{" +
                 "name='" + name + '\'' +
                 '}';
    }
 }

 

配置类

 package com.sy.config;
 
 import com.sy.pojo.User;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 
 @Configuration
 //configuration也会被注册到spring容器中,其本身也是一个@Component
 //@Configuration代表这是一个配置类,和之前使用的beans.xml作用相同
 @ComponentScan("com.sy.pojo")
 public class SyConfig {
     //注册一个bean相当于在xml中写的一个bean标签
     //方法名字为bean标签中的id
     //方法的返回值,就相当于bean标签中的class属性
     @Bean
     public User getUser(){
         //返回的对象,即为注入到容器中的对象
         return new User();
    }
 }

 

测试类

import com.sy.config.SyConfig;
import com.sy.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    @Test
    public void fun(){
        //如果完全使用了配置类方式去做,我们只能通过AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(SyConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user);
    }
}

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

 

10、AOP-代理模式

SpringAOP的底层就是代理模式【面试必问,SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理

  • 动态代理

image-20201202210556990

10.1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决

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

  • 代理角色:代理真实角色,代理真实角色,会做一些附属操作

  • 客户:访问代理对象的人

代码步骤:

  1. 接口

    package com.sy.demo01;
    
    public interface Rent {
        void rent();
    }
  2. 真实角色

    package com.sy.demo01;
    //房东
    public class Host implements Rent{
        @Override
        public void rent() {
            System.out.println("房东要出租房子");
        }
    }
  3. 代理角色

     package com.sy.demo01;
     
     public class Proxy implements Rent{
         private  Host host;
     
         public Proxy(Host host) {
             this.host = host;
        }
     
         public Proxy() {
        }
     
         @Override
         public void rent() {
             seeHouse();
             host.rent();
             heTong();
             fare();
        }
         //看房
         public void seeHouse(){
             System.out.println("中介带你看房");
        }
         //收中介费
         public void fare(){
             System.out.println("收中介费");
        }
         //签合同
         public void heTong(){
             System.out.println("签租赁合同");
        }
     }
  4. 客户端访问代理角色

     package com.sy.demo01;
     
     public class Cilent {
         public static void main(String[] args) {
             //房东要租房子
             Host host = new Host();
             //代理,中介帮房东租房子,代理角色一般会有附加操作
             Proxy proxy = new Proxy(new Host());
     
             proxy.rent();
        }
     }

代理模式的好处

  • 可以使真实角色的操作更加纯粹,不需要去关注一些公共的业务

  • 公共业务交给代理角色,实现了业务的分工

  • 公共业务发生扩展的时候,方便集中管理。

缺点

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

 

10.2、静态代理(加深理解)

代码对应 08-demo02

AOP

image-20201202220313998

10.3、动态代理

  • 动态代理和静态代理角色一样

  • 动态代理的代理类是动态生成的,不是直接写好的

  • 动态代理分为两大类:

    • 基于接口的动态代理

      • 基于接口-JDK动态代理

    • 基于类的动态代理

      • 基于类:cglib

    • java字节码实现

      • Javasist

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

InvocationHandler

  • 调用处理程序,并返回结果

Proxy

  • 生成动态代理实例

动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务

  • 公共业务交给代理角色,实现了业务的分工

  • 公共业务发生扩展时,方便集中管理

  • 一个动态代理类代理的是一个接口,一般对应一类业务

  • 一个动态代理类可以代理多个类,只要实现接口即可。

动态代理工具类(提炼)

package com.sy.demo04;

import com.sy.demo03.Rent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyInvocationHandler implements InvocationHandler {
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

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

动态代理(客户端)

package com.sy.demo04;

import com.sy.demo02.UserService;
import com.sy.demo02.UserServiceImpl;

public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色,不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //设置要代理的对象
        pih.setTarget(userService);
        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();
        proxy.delete();
    }
}

 

11、AOP

11.1、什么是AOP

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

image-20201203163904461

11.2、AOP在Spring中的作用

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

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等...

  • 切面(Aspect):横切关注点被模块化的特殊对象。即,它是一个类

  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

  • 目标(Target):被通知的对象。

  • 代理(Proxy):向目标对象应用通知之后创建的对象。

  • 切入点(PointCut):切面通知执行的”地点“的定义。

  • 连接点(JointPoint):与切入点匹配的执行点。

 

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

image-20201203165618236

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

11.3、使用Spring实现AOP【重点】

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

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

方式一:使用Spring原生API接口(spring-09)

  1. 代理对象接口

    package com.sy.service;
    
    public interface UserService {
        void add();
        void delete();
        void select();
        void update();
    }
  2. 代理对象实现类

    package com.sy.service;
    
    public class UserServiceImpl implements UserService{
        @Override
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        @Override
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        @Override
        public void select() {
            System.out.println("查询了一个用户");
        }
    
        @Override
        public void update() {
            System.out.println("修改了一个用户");
        }
    }
  3. 切面(需要继承Spring的api接口)

     package com.sy.log;
     
     import org.springframework.aop.AfterReturningAdvice;
     
     import java.lang.reflect.Method;
     
     public class AfterLog implements AfterReturningAdvice {
         //returnValue:返回值
         @Override
         public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
             System.out.println("执行了"+method.getName()+"方法;返回结果为:"+returnValue);
        }
     }
  4. 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: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-->
     <bean id="userService" class="com.sy.service.UserServiceImpl"/>
     <bean id="log" class="com.sy.log.Log"/>
     <bean id="afterLog" class="com.sy.log.AfterLog"/>
     <!--方式一:使用原生Spring API接口-->
     <!--配置aop:需要导入aop的约束-->
     <aop:config>
     <!--切入点:expression:表达式execution(要执行的位置)-->
         <aop:pointcut id="pointcut" expression="execution(* com.sy.service.UserServiceImpl.*(..))"/>
     <!--执行环绕增加-->
         <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
         <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
     </aop:config>
 
 </beans>
  1. 测试类

    import com.sy.service.UserService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //动态代理的是接口,不是实现类
            UserService userService = (UserService) context.getBean("userService");
            userService.add();
        }
    }

方法二.自定义切入点类【主要是切面定义】

  1. 自定义类中写具体的方法

  2. 主要是在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: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-->
        <bean id="userService" class="com.sy.service.UserServiceImpl"/>
        <bean id="log" class="com.sy.log.Log"/>
        <bean id="afterLog" class="com.sy.log.AfterLog"/>
    
        <!--方式二:自定义类-->
        <bean id="diy" class="com.sy.diy.DiyPointCut"/>
    
        <aop:config>
        <!--自定义切面,ref要引用的类-->
            <aop:aspect ref="diy">
                <!--切入点-->
                <aop:pointcut id="point" expression="execution(* com.sy.service.UserServiceImpl.*(..))"/>
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after-returning method="after" pointcut-ref="point"/>
                <!--通知-->
    
            </aop:aspect>
        </aop:config>
    </beans>

方法三:使用注解实现

  1. 使用注解,需要标注类为切面,同时使用注解或者在xml中将类注册。

xml中需要开启注解支持

  1. 注解默认使用JDK实现,可以通过设置proxy-target-class来改变实现方式

<!--方式三-->
<bean id="annotationpointcut" class="com.sy.diy.AnnotationPointCut"/>
<!--开启注解支持  JDK(默认 proxy-target-class="false")cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
 package com.sy.diy;
 
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.Signature;
 import org.aspectj.lang.annotation.After;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Before;
 
 //使用注解实现AOP
 @Aspect //标注这个类是一个切面
 public class AnnotationPointCut {
     @Before("execution(* com.sy.service.UserServiceImpl.*(..))")
     public void before(){
         System.out.println("方法执行前");
    }
     @After("execution(* com.sy.service.UserServiceImpl.*(..))")
     public void after(){
         System.out.println("方法执行后");
    }
     //在环绕增强中,我们可以给定一个参数。代表我们要获取处理切入的店
     @Around("execution(* com.sy.service.UserServiceImpl.*(..))")
     public void around(ProceedingJoinPoint joinPoint) throws Throwable {
         System.out.println("环绕前");
         //获得签名
 //       Signature signature = joinPoint.getSignature();
 //       System.out.println("signature"+signature);
         //执行方法
         Object proceed = joinPoint.proceed();
 
         System.out.println("环绕后");
 
 //       System.out.println(proceed);
    }
 }

【注意】:Around相当于一个方法的过滤器

12、整合Mybatis

步骤:

  1. 导入相关Jar包

    • junit

    • mybatis

    • mysql-connector

    • spring-webmvc

    • aop(aspectjweaver)

    • mybatis-spring【new】

    • spring-jdbc

     <dependencies>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>8.0.21</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.1.RELEASE</version>
         </dependency>
      <!--Spring操作数据库的话,需要一个spring-jdbc-->
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-jdbc</artifactId>
             <version>5.2.1.RELEASE</version>
         </dependency>
         <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjweaver</artifactId>
             <version>1.9.6</version>
         </dependency>
         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
         <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

  1. 编写数据源配置

  2. sqlSessionFactory

  3. sqlSessionTemplate

  4. 需要给接口加实现类

  5. 将自己写的实现类,注入到Spring中

  6. 测试

spring-dao.xml

【注意】:spring中引入mybatis-config文件后,设置的属性等,只能有一个

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd">
 
     <!--DataSource:使用spring的数据源替换Mybatis的配置文件
         直接使用Spring提供的JDBC
     -->
     <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
         <property name="url" value="jdbc:mysql://localhost:3306/smbms?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"/>
         <property name="username" value="root"/>
         <property name="password" value="123123"/>
     </bean>
 
     <!--sqlSessionFactory-->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="datasource"/>
         <!--绑定Mybatis配置文件-->
         <property name="configLocation" value="classpath:mybatis-config.xml"/>
         <!--       <property name="mapperLocations" value="classpath:com/sy/mapper/*.xml"/>-->
     </bean>
     <!--相当于mybatis的sqlsession-->
     <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
         <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
         <constructor-arg index="0" ref="sqlSessionFactory"/>
     </bean>
 
 </beans>

 

13、声明式事务

13.1、回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败

  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题

  • 确保完整性和一致性

事务ACID原则:

  • 原子性

  • 一致性

  • 隔离性

    • 多个业务可能操作同一个资源,防止数据损坏

  • 持久性

    • 事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化到存储器中

13.2、Spring中的事务管理

  • 声明式事务:AOP

  • 编程式事务:需要在代码中,进行事务管理(try-catch)

一般使用 声明式事务

需要在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:tx="http://www.springframework.org/schema/tx"
        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/tx
         https://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/aop
         https://www.springframework.org/schema/aop/spring-aop.xsd">
 
     <!--DataSource:使用spring的数据源替换Mybatis的配置文件
         直接使用Spring提供的JDBC
     -->
     <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
         <property name="url" value="jdbc:mysql://localhost:3306/smbms?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"/>
         <property name="username" value="root"/>
         <property name="password" value="123123"/>
     </bean>
 
     <!--sqlSessionFactory-->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="datasource"/>
         <!--绑定Mybatis配置文件-->
         <property name="configLocation" value="classpath:mybatis-config.xml"/>
         <!--       <property name="mapperLocations" value="classpath:com/sy/mapper/*.xml"/>-->
     </bean>
     <!--相当于mybatis的sqlsession-->
     <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
         <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
         <constructor-arg index="0" ref="sqlSessionFactory"/>
     </bean>
 
     <!--配置声明式事务-->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="datasource"/>
     </bean>
     <!--结合AOP实现事务的织入-->
     <!--配置事务通知-->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <!--给哪些方法配置事务-->
         <!--配置事务的传播特性:new propagation-->
         <tx:attributes>
             <tx:method name="*" propagation="REQUIRED"/>
         </tx:attributes>
     </tx:advice>
     <!--配置事务的切入-->
     <aop:config>
         <aop:pointcut id="txPoint" expression="execution(* com.sy.mapper.*.*(..))"/>
         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
     </aop:config>
 </beans>

思考:

为什么需要事务

  • 如果不配置事务,可能存在数据提交不一致的情况下

  • 如果我们不在Spring中去配置声明式事务,我们需要在代码中手动配置事务

  • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题

20、常用注解说明

@Autowired

  • @Autowired : 自动装配通过类型,名字

    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = "xxx")

@Nullable

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

@Resource·

  • @Resource :自动装配通过名字,类型

@Component

  • 组件:放在类上,说明这个类被Spring管理了,就是bean

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

    • dao【@Repository】

    • service【@Service】

    • controller【@Controller】

@Aspect

  • 标注该类为一个切面

@Before

  • 标志该方法在切入点前执行

  •  @Before("execution(* com.sy.service.UserServiceImpl.*(..))")

@After

  • 标志该方法在切入点后执行

  •  @After("execution(* com.sy.service.UserServiceImpl.*(..))")

@Around

  • 此方法相当于切入点的过滤器

  •      @Around("execution(* com.sy.service.UserServiceImpl.*(..))")
         public void around(ProceedingJoinPoint joinPoint) throws Throwable {
             System.out.println("环绕前");
             //获得签名
             Signature signature = joinPoint.getSignature();
             System.out.println("signature"+signature);
             //执行方法
             Object proceed = joinPoint.proceed();
     
             System.out.println("环绕后");
     
             System.out.println(proceed);
        }

#

 

posted @ 2020-12-05 19:11  relo  阅读(263)  评论(0)    收藏  举报