Spring

Spring

1.1 简介

  • Spring:春天--------->给软件行业带来了春天!

  • 2002,首次退出Spring框架的雏形:interface2.1框架

  • Spring框架即以interface2.1框架为基础经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版。

  • Rod Johnson,Spring Framework创始人,著名作者。很难想像Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的不是,然而他的专业不是计算机,而是音乐学。

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

  • SSH:Sruct2 + Spring + Hibernate!

  • SSM:SpringMVC + Spring + Mybatis!

官网:https://spring.io/projects/spring-framework

maven导入依赖

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

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

1.2 优点

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

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

1.3 拓展

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

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

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

2. IOC理论推导

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

我们使用一个set接口实现。已经发生了革命性的变化!

    private UserDao userDao;

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

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

IOC本质

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

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

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

3. HelloSpring

容器概念

org.springframework.context.ApplicationContext接口代表Spring IoC容器,并负责实例化,配置和组装Bean。容器通过读取配置元数据获取有关要实例化,配置和组装哪些对象的指令。

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">


</beans>

在配置中给对象的属性赋值

    <!--使用Spring来创建对象,在Spring这些都称为Bean

    类名 变量名 = new 类名();
    Hello hello = new Hello();

    id = 变量名
    class = new的对象
    property 相当于给对象中的属性设置一个值!
    -->
    <bean id="hello" class="com.dragon.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
  • id属性是标识单个bean定义的字符串。
  • class属性定义Bean的类型并使用完全限定的类名。
  • 是给对象中的属性赋值的
    • name:属性名字
    • value:属性的值

OK,到了现在,我们彻底不用在程序用去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的ICO,一句话搞定:对象由Spring来创建,管理,装配!

实例化容器:当属性为对象时

<bean id="mysqlImpl" class="com.dragon.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.dragon.dao.UserDaoOracleImpl"/>

    <bean id="userServiceImpl" class="com.dragon.Service.UserServiceImpl">
        <!--
        name: 具体的值,基本数据类型,属性名
        ref: 引用上面在Spring容器中创建好的对象
        -->
        <property name="userDao" ref="mysqlImpl"/>
    </bean>
  • ref: 引用上面在Spring容器中创建好的对象

4. IOC创建对象的方式

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

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

    1. 下标赋值

          <bean id="hello" class="com.dragon.pojo.Hello">
              <constructor-arg index="0" value="任博学java"/>
          </bean>
      
    2. 类型赋值

          <bean id="hello" class="com.dragon.pojo.Hello">
              <constructor-arg type="java.lang.String" value="任博学java"/>
          </bean>
      
    3. 参数名赋值

          <bean id="hello" class="com.dragon.pojo.Hello">
              <constructor-arg name="str" value="任博学java"/>
          </bean>
      

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

5. Spring配置

5.1 别名

<!--别名-->
    <alias name="hello" alias="hello2"/>

5.2 Bean中的配置

    <!--
    id:bean的唯一标识符,也就是相当于我们学的对象名
    class:bean对象所对应的全限定名:包名+类型
    name:别名,而且name也可以取多个别名
    -->
    <bean id="hello" class="com.dragon.pojo.Hello" name="hello3">
        <constructor-arg name="str" value="任博学java"/>
    </bean>

5.3 import

导入别的bean配置

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

假设有三个配置文件,最后可以导入applicationContext.xml中

  • 张三
  • 李四
  • 王五
  • applicationContext.xml
<import resource="zhangsan.xml"/>
<import resource="lisi.xml"/>
<import resource="wangwu.xml"/>

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

6. 依赖注入

6.1构造注入

在配置文件加载时候就初始化了

6.2 set方式注入【重点】

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

【环境搭建】

  1. 复杂类型

    public class Address {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        @Override
        public String toString() {
            return "Address{" +
                    "address='" + address + '\'' +
                    '}';
        }
    }
    
    public class Student {
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String[] getBooks() {
            return books;
        }
    
        public void setBooks(String[] books) {
            this.books = books;
        }
    
        public List<String> getHobbys() {
            return hobbys;
        }
    
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
    
        public Map<String, String> getCard() {
            return card;
        }
    
        public void setCard(Map<String, String> card) {
            this.card = card;
        }
    
        public Set<String> getGames() {
            return games;
        }
    
        public void setGames(Set<String> games) {
            this.games = games;
        }
    
        public String getWife() {
            return wife;
        }
    
        public void setWife(String wife) {
            this.wife = wife;
        }
    
        public Properties getInfo() {
            return info;
        }
    
        public void setInfo(Properties info) {
            this.info = info;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", address=" + address.toString() +
                    ", books=" + Arrays.toString(books) +
                    ", hobbys=" + hobbys +
                    ", card=" + card +
                    ", games=" + games +
                    ", wife='" + wife + '\'' +
                    ", info=" + info +
                    '}';
        }
    
        public Address getAddress() {
            return address;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    }
    
  2. 真实测试对象

        <bean id="address" class="com.dragon.pojo.Address">
            <property name="address" value="昌平"/>
        </bean>
    
        <bean id="student" class="com.dragon.pojo.Student">
            <!--普通注入-->
            <property name="name" value="任博学java"/>
    
            <!--bean的ref注入-->
            <property name="address" ref="address"/>
    
            <!--数组-->
            <property name="books">
                <array>
                    <value>book1</value>
                    <value>book2</value>
                    <value>book3</value>
                </array>
            </property>
    
            <!--List-->
            <property name="hobbys">
                <list>
                    <value>篮球</value>
                    <value>足球</value>
                </list>
            </property>
    
            <!--Map-->
            <property name="card">
                <map>
                    <entry key="张三" value="1234"/>
                    <entry key="李四" value="123244"/>
                </map>
            </property>
    
            <!--Set-->
            <property name="games">
                <set>
                    <value>lol</value>
                    <value>bob</value>
                </set>
            </property>
    
            <!--null-->
            <property name="wife">
                <null/>
            </property>
    
            <!--Properties-->
            <property name="info">
                <props>
                    <prop key="学号">1234</prop>
                    <prop key="性别"></prop>
                </props>
            </property>
        </bean>
    

6.3 拓展方式注入

p-namespace允许您使用bean元素的属性(而不是嵌套的 <property/>元素)来描述协作Bean的属性值,或同时使用这两者。

Spring支持带有XML定义的命名空间的可扩展配置格式。beans本章讨论的配置格式在XML Schema文档中定义。但是,p命名空间未在XSD文件中定义,仅存在于Spring的核心中。

<!--在XSD文件中定义p-namespace-->
xmlns:c="http://www.springframework.org/schema/c"

<!--在XSD文件中定义c-namespace-->
xmlns:p="http://www.springframework.org/schema/p"
  • p命名空间注入,可以直接注入属性的值:property

    <bean id="user" class="com.dragon.pojo.User" p:name="任博" p:age="18" />
    
  • c命名空间注入,通过构造器注入:construct-args

    <bean id="user" class="com.dragon.pojo.User" c:name="任博" c:age="18" />
    

6.4 bean的作用域

ScopeDescription
singleton(默认值)将每个Spring IoC容器的单个bean定义范围限定为单个对象实例。
prototype将单个bean定义的作用域限定为任意数量的对象实例。
request将单个bean定义的范围限定为单个HTTP请求的生命周期。也就是说,每个HTTP请求都有一个在单个bean定义后面创建的bean实例。仅在可感知网络的Spring上下文中有效ApplicationContext
session将单个bean定义的范围限定为HTTP的生命周期Session。仅在可感知网络的Spring上下文中有效ApplicationContext
application将单个bean定义的作用域限定为的生命周期ServletContext。仅在可感知网络的Spring上下文中有效ApplicationContext
websocket将单个bean定义的作用域限定为的生命周期WebSocket。仅在可感知网络的Spring上下文中有效ApplicationContext
  1. 单例模式(Spring默认机制)

    <bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
    
  2. 原型模式(每次从容器中get的时候,都会产生一个新的对象!)

    <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
    

7.Bean的自动装配

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

在Spring中有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示的配置
  3. 隐式的自动装配bean 【重要】
no(默认)无自动装配。Bean引用必须由ref元素定义。对于较大的部署,建议不要更改默认设置,因为明确指定协作者可以提供更好的控制和清晰度。在某种程度上,它记录了系统的结构。
byName按属性名称自动布线。Spring查找与需要自动装配的属性同名的bean。例如,如果一个bean定义被设置为按名称自动装配并且包含一个master属性(即它具有一个 setMaster(..)方法),那么Spring将查找一个名为的bean定义,master并使用它来设置该属性。
byType如果容器中恰好存在一个属性类型的bean,则使该属性自动连接。如果存在多个错误,则会引发致命异常,这表明您可能无法byType对该bean使用自动装配。如果没有匹配的bean,则什么都不会发生(未设置该属性)。
constructor类似于byType但适用于构造函数参数。如果容器中不存在构造函数参数类型的一个bean,则将引发致命错误。

7.1 byName和byType自动装配

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

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

小结:

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

7.2使用注解实现自动装配

  1. 导入约束: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(Spring)容器中存在的,且符合名字buName!

科普:

@Nullable  //字段标记了这个注解的话,说明可以为null
@Autowired(required = false)  //如果定义了这个属性为false的话,说明这个对象可以为null,否则!null

@Qualifier(value = “xxx”)

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

示例:

    @Autowired
    @Qualifier(value = "cat")  //指定下边的cat对象
    private Cat cat;
    <bean id="cat" class="com.dragon.pojo.Cat"/>
    <bean id="cat1" class="com.dragon.pojo.Cat"/>

@Resource(name = “xxx”) java注解

    @Resource(name = "dog")
    private Dog dog;
    <bean id="dog" class="com.dragon.pojo.Dog"/>
    <bean id="dog1" class="com.dragon.pojo.Dog"/>

小结:@Autowired和@Resource的区别

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

8. 使用注解开发

设置注解支持

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

测试不用设置bean,注解开发

  1. 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"
           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/>
        <!--指定要扫描的包,这个包下的注解就会生效-->
        <context:component-scan base-package="com.dragon.pojo"/>
    
    </beans>
    
  2. 属性如何注入

    @Component //组件--->等价于 <bean id="user" class="com.dragon.pojo.User" />
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        @Value("dragon2")  //等价于<property name="name" value="dragon2" />
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 衍生的注解

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

    • dao【@Repository】
    • service 【@Service 】
    • controller 【@Controller 】

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

  4. 作用域

    @Scope("singleton")  //给其设置为单例模式
    
  5. 小结

    xml 于 注解:

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

    xml 于 注解 最佳实践:

    • xml用来管理bean;

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

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

      <!--开启注解支持-->
      <context:annotation-config/>
      <!--指定要扫描的包,这个包下的注解就会生效,指定注解的位置-->
      <context:component-scan base-package="com.dragon.pojo"/>
      

@Component 组件

等价于

 <bean id="user" class="com.dragon.pojo.User" />

总而言之意思就是想到于在配置中设置的bean,实例化对象

这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中

@Scope 设置作用域默认为单例

  • singleton单例:

    • 仅管理一个singleton bean的一个共享实例,并且所有对具有ID或与该bean定义相匹配的ID的bean的请求都会导致该特定的bean实例由Spring容器返回。

      换句话说,当您定义一个bean定义并且其作用域为单例时,Spring IoC容器将为该bean定义所定义的对象创建一个实例。该单个实例存储在此类单例bean的高速缓存中,并且对该命名bean的所有后续请求和引用都返回该高速缓存的对象

  • propotype原型:

    • 每次对特定bean提出请求时,bean部署的非单一原型范围都会导致创建一个新bean实例。也就是说,该Bean被注入到另一个Bean中,或者您可以通过getBean()容器上的方法调用来请求它。通常,应将原型作用域用于所有有状态Bean,将单例作用域用于无状态Bean。

@Bean

在java类中配置bean

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

@Value(“dragon”)

给属性赋值

    @Value("dragon")  //属性注入值,等价于<property name="name" value="dragon2" />
    public void setName(String name) {
        this.name = name;
    }

9.使用java的方式配置spring

  1. 实体类

    //这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
    //@Component //组件--->等价于 <bean id="user" class="com.dragon.pojo.User" />
    //@Scope("singleton")
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        @Value("dragon")  //属性注入值,等价于<property name="name" value="dragon2" />
        public void setName(String name) {
            this.name = name;
        }
    }
    
  2. 配置文件

    //这个也会spring容器托管,注册到容器中,因为他本来就是一个@Component
    //@Configuration 代表这是一个配置类,就和我们之前看的applicationContext.xml一样
    //@Configuration
    
    //指定配置的对象
    //@ComponentScan("com.dragon.pojo")
    public class DragonConfig {
    
        //注册一个bean,就相当于我们之前写的bean的一个标签
        //这个方法的名字,就相当于bean标签中的id属性
        //这个方法的返回值,就相当于bena标签中的class属性
        @Bean
        public User getUser() {
            return new User();//就是返回要注入到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"
           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/>
        <!--指定要扫描的包,这个包下的注解就会生效,也就是注解的位置-->
        <context:component-scan base-pa ckage="com.dragon.pojo"/>
    
    </beans>
    
  3. 测试类

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

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

10. 代理模式

为什么要学习代理模式?因为这就是springAOP的底层! 【SpringAOP 和 SpringMVC】

10.1 静态代理

角色分析:

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

测试步骤:

  1. 接口

    //出租房
    public interface RentHouse {
        //出租房
        public void rentHouse();
    }
    
  2. 真实角色

    //房东角色(被代理角色)
    public class LandLord implements RentHouse{
    
        public void rentHouse() {
            System.out.println("房东出租房!");
        }
    }
    
  3. 代理角色

    //中介(代理人)
    public class Proxy implements RentHouse {
        private LandLord landLord;
    
        public Proxy() {
        }
    
        public Proxy(LandLord landLord) {
            this.landLord = landLord;
        }
    
        public void rentHouse() {
            landLord.rentHouse();
            lookAsHouse();
            contract();
            agencyFee();
        }
    
        //中介的一些附属操作
        //1.带客户看房
        public void lookAsHouse(){
            System.out.println("中介带客户看房");
        }
    
        //2.签合同
        public void contract() {
            System.out.println("让客户签合同");
        }
    
        //3.收中介费
        public void agencyFee() {
            System.out.println("收取中介费");
        }
    }
    
  4. 客户端访问角色

    //租房客(客户)
    public class Client {
        @Test
        public void rentHouseTest() {
            //实例化房东
            LandLord landLord = new LandLord();
    
            //找中介,然后中介介绍landlord的房
            Proxy proxy = new Proxy(landLord);
            proxy.rentHouse();
        }
    }
    
    

代理模式的好处:

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

缺点:

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

10.2 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们之前一样直接写好的
  • 动态代理分为两大类:基于接口的动态代理;基于类的动态代理
    • 基于接口:JDK动态代理【我们在这里使用】
    • 基于类:cglib
    • java字节码实现:javasist

需要理解:Proxy:代理;InvoationHandler:调用处理程序

动态代理工具类:

public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Object target;

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

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

    //处理代理实例,并返回结果!
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //得到执行的的方法名
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

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

实现类:

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

        //设置需要代理的对象
        proxyInvocationHandler.setTarget(userService);

        //动态生成代理类
        UserService proxy = (UserService) proxyInvocationHandler.getProxy();

        proxy.update();
    }
}

动态代理的好处:

  • 可以使用真实角色的操作,使其更加纯粹!不用去关注一些公共的业务。
  • 公共业务交给代理角色,实现了业务分工!
  • 公共业务放生扩展的时候,方便集中管理!
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务!
  • 一个动态代理类可以代理多个类,只要实现了同一个接口即可!

11. AOP

11.1 什么是AOP

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

11.2 AOP在Spring的作用

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

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

11.3 使用Spring实现AOP

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

    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
    </dependencies>

方式一:使用原生Spring API接口

主要是API接口实现

业务类

public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("增加了一个用户");
    }

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

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

    public void select() {
        System.out.println("查询了一个用户");
    }
}

日志类

//执行前
public class BeforeLog implements MethodBeforeAdvice {

    /*
     method:要执行的对象目标的方法
     args:参数
     target:目标对象
    */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

//执行后
public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回值为:"+o);
    }
}

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"
       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.dragon.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.dragon.Log.BeforeLog"/>
    <bean id="afterLog" class="com.dragon.Log.AfterLog"/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <aop:config>
        <!--切入点:execution:表达式(要执行的位置!)-->
        <aop:pointcut id="pointcut" expression="execution(* com.dragon.service.UserServiceImpl.*(..))"/>

        <!--执行前后增加日志-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>


</beans>

测试类

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

方式二:自定义实现AOP

主要是切面定义

自定义类

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

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

配置文件

<?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 id="userService" class="com.dragon.service.UserServiceImpl"/>
    
    <!--方式二:自定义类-->
    <bean id="diyPointCut" class="com.dragon.diy.diyPointCut"/>

    <aop:config>
        <!--自定义切面,ref要引用的类-->
        <aop:aspect ref="diyPointCut">
            <!--切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.dragon.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

</beans>

方式三:使用注解实现AOP

spring配置文件,开启AOP注解支持

<?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 id="userService" class="com.dragon.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.dragon.Log.BeforeLog"/>
    <bean id="afterLog" class="com.dragon.Log.AfterLog"/>


    <!--方式三:使用注解实现AOP-->
    <bean id="annotationPointCut" class="com.dragon.annotation.annotationPointCut"/>
    <!--开启注解支持  JDK(默认->proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy/>

</beans>

注解类

@Aspect //标注这是一个切面类
@Component  //在spring容器中配置
public class annotationPointCut {

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

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

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

}

12. 整合Mybatis

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aop织入
    • mybaits-spring【new】
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.22</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.9.RELEASE</version>
            </dependency>
            <!--spring操作数据库的话还需要一个spring-jdbc-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.9.RELEASE</version>
            </dependency>
            <!--aop织入包-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.6</version>
            </dependency>
            <!--spring-mybaits整合包-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.5</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
            </dependency>
        </dependencies>
    
  2. 编写配置文件

  3. 测试

12.1 回顾Mybatis

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

12.2 Mybatis-Spring整合

什么是Mybatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。

整合步骤:

  1. 编写spring配置文件

    1. 编写数据源配置 DriverManagerDataSource (连接数据库的配置)

    2. 从SqlSessionFactoryBean类中得到SqlSessionFactory

    3. 把配置好的数据源给到SqlSessionFactory,然后再注册Mapper.xml文件

    4. 把SqlSessionFactory给到SqlSessionTemplate类

    5. 从SqlSessionTemplate类中得到sqlSession

      <?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">
      
          <!--DataSource使用Spring的数据源替换Mybatis的配置
          我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
          -->
          <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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
              <property name="username" value="root"/>
              <property name="password" value="1234"/>
          </bean>
      
          <!--SqlSessionFactory-->
          <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource"/>
              <!--绑定mybatis配置文件-->
              <property name="configLocation" value="classpath:mybatisConfig.xml"/>
              <!--绑定Mapper.xml文件-->
              <property name="mapperLocations" value="classpath:com/dragon/mapper/*.xml"/>
          </bean>
      
          <!--SqlSessionTemplate:就是我们使用的sqlSession-->
          <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
              <constructor-arg index="0" ref="SqlSessionFactory"/>
          </bean>
      
      </beans>
      
  2. 给接口加实现类【】

    public class UserMapperImpl implements UserMapper {
    
        //之前使用的sqlSession,现在使用sqlSessionTemplate;
        private SqlSessionTemplate sqlSession;
    
        public void setSqlsession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
    
  3. 将实现类注入到spring配置中

    • 把上面配置文件得到的sqlSession给到上边的实现类
    <?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">
    
        <import resource="Spring-dao.xml"/>
    
        <bean id="userMapper" class="com.dragon.mapper.UserMapperImpl">
            <property name="sqlsession" ref="sqlSession"/>
        </bean>
    </beans>
    
  4. 测试

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

12.3 用SqlSessionDaoSupport精简上边的代码

SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法。

实现类

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    //继承之后可以直接使用sqlSession了
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

编写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"
       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">

    <!--DataSource使用Spring的数据源替换Mybatis的配置
    我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
    -->
    <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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>

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

将实现类注入到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"
       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">

    <import resource="Spring-dao.xml"/>
    
    <!--直接把sqlSessionFactory丢给UserMapperImpl2中继承的sqlSessionDaoSupport-->
    <bean id="userMapper" class="com.dragon.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="SqlSessionFactory"/>
    </bean>
</beans>

小结:继承sqlSSessionDaoSupport后,可以直接省略掉配置sqlSessionTemplate的bean,直接直接把sqlSessionFactory丢给继承sqlSessionDaoSupport的类

13. 声明式事务

1. 回顾事务

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

事务ACID原则:

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

2. spring中的事务管理

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

声明式事务

一个使用 MyBatis-Spring 的其中一个主要原因是它允许 MyBatis 参与到 Spring 的事务管理中。而不是给 MyBatis 创建一个新的专用事务管理器,MyBatis-Spring 借助了 Spring 中的 DataSourceTransactionManager 来实现事务管理。

实现步骤:

  1. 先配置mybatis和spring整合
  2. 通过DataSourceTransactionManager类配置声明式事务
    • 把上边的dataSource给到配置的这个bean
  3. 配置事务通知
    • transaction-manager="transactionManager“: 把DataSourceTransactionManager类给到配置事务通知中的属性transaction-manager
  4. 用aop切入设置好的事务通知
    • 设置切入点(在哪里切入这个事务)---->设置的属性:expression=“execution(* com.dragon.mapper..(…))”
    • 把刚才配置好的事务给到这个切入点 —> advice-ref=“txAdvice”
  5. ok!事务切入成功
<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

<!--DataSource使用Spring的数据源替换Mybatis的配置
    我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
    -->
    <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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>

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

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

    <!--结合AOP实现事务的织入;配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给那些方法配置事务;事务的传播性:propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

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

</beans>

【提取重要代码】

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

    <!--结合AOP实现事务的织入;配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给那些方法配置事务;事务的传播性:propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值