首页 > 其他分享 >Spring学习

Spring学习

时间:2022-12-02 18:11:25浏览次数:56  
标签:Spring void 代理 class 学习 spring println public

Spring学习

1. Spring

1.1 简介

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

  • 2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。

  • 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。

  • 很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。

  • Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术

官网 :https://docs.spring.io/spring-framework/docs/current/reference/html/overview.html#overview

官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

配置文件:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>6.0.2</version>
</dependency>

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

1.2 优点

  1. Spring是一个开源免费的框架 , 容器;
  2. Spring是一个轻量级的框架 , 非侵入式的;
  3. 控制反转(IoC) , 面向切面编程(Aop)
  4. 支持事务的处理 , 对框架整合的支持;

一句话概括:

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

1.3 组成

spring-1

1.4 扩展

spring-2

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

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

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

2. IOC理论推导

2.1 IoC基础

新建一个空白的maven项目

分析实现

我们先用我们原来的方式写一段代码 .

  1. 先写一个UserDao接口

    public interface UserDao {
        void getUser();
    }
    
  2. 再去写Dao的实现类

    public class UserDaoImpl implements UserDao {
        @Override
        public void getUser() {
            System.out.println("UserDaoImpl");
        }
    }
    
  3. 然后去写UserService的接口

    public interface UserService {
        void getUser();
    }
    
  4. 最后写Service的实现类

    public class UserServiceImpl implements UserService {
       private UserDao userDao = new UserDaoImpl();
    
       @Override
       public void getUser() {
           userDao.getUser();
      }
    }
    
  5. 测试一下

    @Test
    public void test(){
       UserService service = new UserServiceImpl();
       service.getUser();
    }
    

    这是我们原来的方式 , 开始大家也都是这么去写的对吧 . 那我们现在修改一下 .

    spring-3

    • 把Userdao的实现类增加一个

      public class UserDaoImpl2 implements UserDao {
          @Override
          public void getUser() {
              System.out.println("UserDaoImpl2");
          }
      }
      
    • 紧接着我们要去使用UserDaoImpl2的话 , 我们就需要去service实现类里面修改对应的实现

      public class UserServiceImpl implements UserService {
         private UserDao userDao = new UserDaoImpl2();
      
         @Override
         public void getUser() {
             userDao.getUser();
        }
      }
      
    • 再假设, 我们再增加一个Userdao的实现类

      public class UserDaoOracleImpl implements UserDao {
         @Override
         public void getUser() {
             System.out.println("Oracle获取用户数据");
        }
      }
      
    • 那么我们要使用Oracle , 又需要去service实现类里面修改对应的实现 . 假设我们的这种需求非常大 , 这种方式就根本不适用了, 甚至反人类对吧 , 每次变动 , 都需要修改大量代码 。这种设计的耦合性太高了, 牵一发而动全身

  6. 那我们如何去解决呢 ?

    • 我们可以在需要用到他的地方 , 不去实现它 , 而是留出一个接口 , 利用set , 我们去代码里修改下

      public class UserServiceImpl implements UserService {
          private static UserDao userDao;
      
          public void setUserDao(UserDao userDao) {
              this.userDao = userDao;
          }
      
          @Override
          public void getUser() {
              userDao.getUser();
          }
      }
      
    • 现在去我们的测试类里 , 进行测试

      @Test
      public void test() {
          UserServiceImpl userService = new UserServiceImpl();
          userService.setUserDao(new UserDaoImpl2());
      }
      

​ 大家发现了区别没有 ? 可能很多人说没啥区别。但是同学们 , 他们已经发生了根本性的变化 , 很多地方都不一样了。仔细去思考一下 , 以前所有东西都是由程序去进行控制创建 , 而现在是由我们自行控制创建对象 , 把主动权交给了调用者。程序不用去管怎么创建,怎么实现了。它只负责提供一个接口。

spring-4

​ 这种思想 , 从本质上解决了问题 , 我们程序员不再去管理对象的创建了 , 更多的去关注业务的实现 . 耦合性大大降低 . 这也就是IOC的原型 !

2.2 IOC本质

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

spring-5

IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

spring-6

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

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

3. HelloSpring

导入Jar包

注 : spring 需要导入commons-logging进行日志记录 . 我们利用maven , 他会自动下载对应的依赖项 .

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>

编写代码

  1. 编写一个Hello实体类

    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 + '\'' +
                    '}';
        }
    }
    
  2. 编写我们的spring文件 , 这里我们命名为beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--bean就是java对象,由spring创建和管理-->
        <bean id="hello" class="com.LEEZ.pojo.Hello">
            <property name="str" value="Hello World"/>
        </bean>
    
    </beans>
    
  3. 测试

    @Test
    public void test() {
        //解析beans.xml文件 , 生成管理相应的Bean对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //解析beans.xml文件 , 生成管理相应的Bean对象
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello);
    }
    

思考

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

这个过程就叫控制反转 :

  • 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
  • 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .

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

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

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

修改案例一

我们在案例一中, 新增一个Spring配置文件beans.xml

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

    <!--bean就是java对象,由spring创建和管理-->
    <bean id="userDaoImpl" class="com.LEEZ.dao.UserDaoImpl"/>
    <bean id="userDaoImpl2" class="com.LEEZ.dao.UserDaoImpl2"/>

    <bean id="userServiceImpl" class="com.LEEZ.service.UserServiceImpl">
        <!--注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写-->
        <!--引用另外一个bean , 不是用value 而是用 ref-->
        <property name="userDao" ref="userDaoImpl2"/>
    </bean>
</beans>

测试

@Test
public void test() {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
    userServiceImpl.getUser();
}

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

4. IOC创建对象方式

通过无参构造方法来创建

  1. User.java

    package com.LEEZ.pojo;
    
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public User() {
            System.out.println("进入了无参构造");
        }
    
        public void show() {
            System.out.println("name:"+ this.name);
        }
    }
    
  2. beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--bean就是java对象,由spring创建和管理-->
        <bean id="user" class="com.LEEZ.pojo.User">
            <property name="name" value="LEEZ"/>
        </bean>
    
    </beans>
    
  3. 测试类

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }
    

结果可以发现,在调用show方法之前,也就是context.getBean时,User对象已经通过无参构造初始化了!

通过有参构造来创建

  1. User.java

    package com.LEEZ.pojo;
    
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public User() {
            System.out.println("进入了无参构造");
        }
    
        public User(String name){
            this.name = name;
        }
    
        public void show() {
            System.out.println("name:"+ this.name);
        }
    }
    
  2. beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--bean就是java对象,由spring创建和管理-->
        <!--无参构造初始化对象-->
        <bean id="user0" class="com.LEEZ.pojo.User">
            <property name="name" value="LEEZ"/>
        </bean>
    
        <!--有参构造初始化对象-->
        <!--初始化对象的第一种方式,通过构造器下标赋值-->
        <bean id="user1" class="com.LEEZ.pojo.User">
            <constructor-arg index="0" value="CV攻城狮"/>
        </bean>
    
        <!--初始化对象的第二种方式,通过参数类型,不建议使用-->
        <bean id="user2" class="com.LEEZ.pojo.User">
            <constructor-arg type="java.lang.String" value="CV攻城狮-LEEZ"/>
        </bean>
    
        <!--初始化对象的第三种方式,直接通过参数名来设置-->
        <bean id="user3" class="com.LEEZ.pojo.User">
            <constructor-arg name="name" value="leez-cv"/>
        </bean>
    </beans>
    
  3. 测试

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user0 = (User) context.getBean("user0");
        user0.show();
    
        User user1 = (User) context.getBean("user1");
        user1.show();
    
        User user2 = (User) context.getBean("user2");
        user2.show();
    
        User user3 = (User) context.getBean("user3");
        user3.show();
    }
    

结论:在配置文件加载的时候,其中管理的对象都已经初始化了!即new ClassPathXmlApplicationContext("beans.xml")时,beans.xml中所有的bean都已经被初始化了

5. Spring配置

别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="user0" alias="userNew"/>

Bean的配置

<!--bean就是java对象,由Spring创建和管理-->

<!--
   id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
   如果配置id,又配置了name,那么name是别名
   name可以设置多个别名,可以用逗号,分号,空格隔开
   如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;

 class是bean的全限定名=包名+类名
-->
<bean id="user0" name="u0 uu,U0;uu0" class="com.LEEZ.pojo.User">
   <property name="name" value="LEEZ"/>
</bean>

import

团队的合作通过import来实现,将多个beans.xml导入到最终的applicationContext.xml

<import resource="beans.xml"/>

6. DI注入

概念

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指Bean对象的创建依赖于容器,Bean对象的依赖资源;
  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配;

6.1 构造器注入

我们在之前的案例已经讲过了

6.2 Set 注入 (重点)

要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .

测试pojo类 :

Student.java

@Data
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
}

Address.java

@Data
public class Address {
    private String address;
}

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
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.LEEZ.pojo.Address">
        <property name="address" value="五邑大学"/>
    </bean>

    <bean id="student" class="com.LEEZ.pojo.Student">
        <!--第一种,普通值注入,直接value-->
        <property name="name" value="LEEZ"/>
        <!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>
        <!--第三种,数组-->
        <property name="books">
            <array>
                <value>《红楼梦》</value>
                <value>《三国演义》</value>
                <value>《西游记》</value>
                <value>《水浒传》</value>
            </array>
        </property>
        <!--第四种,List集合-->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>打代码</value>
                <value>打游戏</value>
            </list>
        </property>
        <!--第五种,map集合-->
        <property name="card">
            <map>
                <entry key="身份证" value="111122233334445555"/>
                <entry key="性别" value="男"/>
            </map>
        </property>
        <!--第六种,set集合-->
        <property name="games">
            <set>
                <value>塞尔达</value>
                <value>宝可梦</value>
            </set>
        </property>
        <!--第七种,null值-->
        <property name="wife">
            <null/>
        </property>
        <!--第八种,properties-->
        <property name="info">
            <props>
                <prop key="driver">com.mysql.jdbc.Driver</prop>
                <prop key="url">jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT</prop>
                <prop key="username">root</prop>
                <prop key="password"/>
            </props>
        </property>
   </bean>
</beans>

6.3 p命名和c命名注入

  1. P命名空间注入 : 需要在头文件中加入约束文件

     导入约束 : xmlns:p="http://www.springframework.org/schema/p"
     
     <!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
     <bean id="user" class="com.kuang.pojo.User" p:name="狂神" p:age="18"/>
    
  2. c 命名空间注入 : 需要在头文件中加入约束文件

    导入约束 : xmlns:c="http://www.springframework.org/schema/c"
     <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
     <bean id="user" class="com.kuang.pojo.User" c:name="狂神" c:age="18"/>
    

结论:p命名注入本质是set注入,c命名注入本质是构造器注入。

6.4 bean的作用域

spring-7

  1. 单例模式(spring默认)

    <bean id="student" class="com.LEEZ.pojo.Student" scope="singleton"/>
    
  2. 原型模式:每次从容器中get的时候,都会产生一个新对象

    <bean id="student" class="com.LEEZ.pojo.Student" scope="prototype"/>
    
  3. 其余的request、session、application这些只能在web开发中使用

7. Bean自动装配

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  1. 在xml中显式配置;
  2. 在java中显式配置;
  3. 隐式的bean发现机制和自动装配。

7.1 测试环境

  1. 新建项目

  2. Cat.java和Dog.java

    public class Cat {
        public void shout() {
            System.out.println("喵喵喵");
        }
    }
    
    public class Dog {
        public void shout() {
            System.out.println("汪汪汪");
        }
    }
    
  3. People.java

    @Data
    public class People {
        private String name;
        private Cat cat;
        private Dog dog;
    }
    
  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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="cat" class="com.LEEZ.pojo.Cat"/>
        <bean id="dog" class="com.LEEZ.pojo.Dog"/>
    
        <bean id="people" class="com.LEEZ.pojo.People">
            <property name="name" value="LEEZ"/>
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
        </bean>
    </beans>
    
  5. 测试

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        People people = context.getBean(People.class);
        people.getCat().shout();
        people.getDog().shout();
    }
    

7.2 ByName自动装配

  1. applicationContext.xml在bean加上autowire=“byName”

    <bean id="people" class="com.LEEZ.pojo.People" autowire="byName">
        <property name="name" value="LEEZ"/>
    </bean>
    
  2. 再次测试,结果依旧成功输出!

  3. 我们将 cat 的bean id修改为 catXXX

  4. 再次测试, 执行时报空指针java.lang.NullPointerException。因为按byName规则找不对应set方法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

小结:

当一个bean节点带有 autowire byName的属性时。

  1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。

7.3 ByType

autowire byType (按类型自动装配)

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

NoUniqueBeanDefinitionException

测试:

  1. 将user的bean配置修改一下 : autowire=“byType”

    <bean id="people" class="com.LEEZ.pojo.People" autowire="byType">
        <property name="name" value="LEEZ"/>
    </bean>
    
  2. 测试,正常输出

  3. 在注册一个cat 的bean对象!

    <bean id="cat" class="com.LEEZ.pojo.Cat"/>
    <bean id="cat2" class="com.LEEZ.pojo.Cat"/>
    <bean id="dog" class="com.LEEZ.pojo.Dog"/>
    
    <bean id="people" class="com.LEEZ.pojo.People" autowire="byType">
        <property name="name" value="LEEZ"/>
    </bean>
    
  4. 测试,报错:NoUniqueBeanDefinitionException

  5. 删掉cat2,将cat的bean名称改掉!测试!因为是按类型装配,所以并不会报异常,也不影响最后的结果。甚至将id属性去掉,也不影响结果。

这就是按照类型自动装配!

7.4 使用注解实现自动装配

jdk1.5开始支持注解,spring2.5开始全面支持注解。

准备工作:利用注解的方式注入属性。

  1. 在spring配置文件中引入context文件头

    xmlns:context="http://www.springframework.org/schema/context"
    
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    
  2. 开启属性注解支持

    <context:annotation-config/>
    
  3. @Autowired

    • @Autowired是按类型自动转配的,不支持id匹配。
    • 需要导入 spring-aop的包!

测试:

  1. 将User类中的set方法去掉,使用@Autowired注解

    public class People {
       @Autowired
       private Cat cat;
       @Autowired
       private Dog dog;
       private String name;
    
       public Cat getCat() {
           return cat;
      }
       public Dog getDog() {
           return dog;
      }
       public String getName() {
           return name;
      }
    }
    
  2. 此时配置文件内容

    <context:annotation-config/>
    
    <bean id="dog" class="com.LEEZ.pojo.Dog"/>
    <bean id="cat" class="com.LEEZ.pojo.Cat"/>
    <bean id="people" class="com.LEEZ.pojo.People"/>
    
  3. 测试,成功输出结果!

注意:

  • @Autowired(required=false) 说明:false,对象可以为null;true,对象必须存对象,不能为null。

    //如果允许对象为null,设置required = false,默认为true
    @Autowired(required = false)
    private Cat cat;
    
  • @Nullable说明:如果字段标记了这个注解,说明这个字段可以为null。

    @Nullable
    private Cat cat;
    

7.6 @Qualifier

  • @Autowired默认是根据类型自动装配的,当有多个相同类型时,则根据ByName进行自动装配,若名字也相同时,加上@Qualifier则可以根据特定的byName方式自动装配
  • @Qualifier不能单独使用。

测试实验步骤:

  1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

    <bean id="dog1" class="com.kuang.pojo.Dog"/>
    <bean id="dog2" class="com.kuang.pojo.Dog"/>
    <bean id="cat1" class="com.kuang.pojo.Cat"/>
    <bean id="cat2" class="com.kuang.pojo.Cat"/>
    
  2. 没有加Qualifier测试,直接报错

  3. 在属性上添加Qualifier注解

    @Autowired
    @Qualifier(value = "cat2")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog2")
    private Dog dog;
    

    测试,成功输出!

7.7 @Resource

  • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  • 其次再进行默认的byName方式进行装配;
  • 如果以上都不成功,则按byType的方式自动装配。
  • 都不成功,则报异常。

实体类

public class User {
   //如果允许对象为null,设置required = false,默认为true
   @Resource(name = "cat2")
   private Cat cat;
   @Resource
   private Dog dog;
   private String str;
}

beans.xml

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

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

测试:结果OK

配置文件2:beans.xml , 删掉cat2

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>

实体类上只保留注解

@Resource
private Cat cat;
@Resource
private Dog dog;

结果:OK

结论:先进行byName查找,失败;再进行byType查找,成功。

小结

@Autowired与@Resource异同:

  1. @Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
  2. @Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
  3. @Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
  4. 它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。

8. 使用注解开发

8.1 说明

在spring4之后,想要使用注解形式,必须得要引入aop的包

spring-8

在配置文件当中,还得要引入一个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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
</beans>

8.2 Bean的实现

我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!

1、配置扫描哪些包下的注解

<!--指定注解扫描包-->
<context:component-scan base-package="com.LEEZ.pojo"/>

2、在指定包下编写类,增加注解

// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
@Component("user")
public class User {
   public String name = "LEEZ";
}

3、测试

@Test
public void test(){
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean(User.class);
        System.out.println(user.name);
    }
}

8.3 属性注入

使用注解注入属性

1、可以不用提供set方法,直接在直接名上添加@value(“值”)

// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
@Component("user")
public class User {
   @Value("LEEZ")
   // 相当于配置文件中 <property name="name" value="LEEZ"/>
   public String name;
}

2、如果提供了set方法,在set方法上添加@value(“值”);

@Component("user")
public class User {

    public String name;

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

衍生注解

我们这些注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!

@Component三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

  • dao层:@Respository
  • service层:@Service
  • servlet层(controller层):@Controller

写上这些注解,就相当于将这个类交给Spring管理装配了!

8.4 自动装配注解

在Bean的自动装配已经讲过了,可以回顾!

8.5 作用域

@scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
  • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Controller("user")
@Scope("prototype")
public class User {
   @Value("LEEZ")
   public String name;
}

8.6 小结

XML与注解比较

  • XML可以适用任何场景 ,结构清晰,维护方便
  • 注解不是自己提供的类使用不了,开发简单方便

xml与注解整合开发 :推荐最佳实践

  • xml管理Bean
  • 注解完成属性注入
  • 使用过程中, 可以不用扫描,扫描是为了类上的注解
<context:annotation-config/>  

作用:

  • 进行注解驱动注册,从而使注解生效
  • 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
  • 如果不扫描包,就需要手动配置bean
  • 如果不加注解驱动,则注入的值为null!

8.7 基于Java类进行配置

JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。

测试:

1、编写一个实体类,Dog

public class Dog {
    @Value("旺财")
    public String name;
}

2、新建一个config配置包,编写一个MyConfig配置类

@Configuration//代表这是一个配置类
public class MyConfig {

    @Bean//通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
    public Dog dog() {
        return new Dog();
    }
}

3、测试

@Test
public void test() {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
    Dog dog = applicationContext.getBean(Dog.class);
    System.out.println(dog.name);
}

4、成功输出结果!

导入其他配置如何做呢?

1、我们再编写一个配置类!

@Configuration  //代表这是一个配置类
public class MyConfig2 {
}

2、在之前的配置类中我们来选择导入这个配置类

@Configuration
@Import(MyConfig2.class)  //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {

   @Bean
   public Dog dog(){
       return new Dog();
  }

}

关于这种Java类的配置方式,我们在之后的SpringBoot 和 SpringCloud中还会大量看到,我们需要知道这些注解的作用即可!

9. 代理模式

为什么要学习代理模式? 因为这就是Spring AOP的底层。

代理模式的分类:

  • 静态代理
  • 动态代理

spring-9

9.1 静态代理

静态代理角色分析

  • 抽象角色 : 一般使用接口或者抽象类来实现
  • 真实角色 : 被代理的角色
  • 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .
  • 客户 : 使用代理角色来进行一些操作 .

代码实现

Rent . java 即抽象角色

//抽象角色:租房
public interface Rent {
   public void rent();
}

Host . java 即真实角色

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

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("收中介费");
  }
}

Client . java 即客户

//客户类,一般客户都会去找代理!
public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
        //中介代理房东
        Proxy proxy = new Proxy(host);
        //你找中介租房,即中介代理房东出租房子给你
        proxy.rent();
    }
}

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

静态代理的好处:

  • 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
  • 公共的业务由代理来完成 . 实现了业务的分工 ,
  • 公共业务发生扩展时变得更加集中和方便 .

缺点 :

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

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

9.2 静态代理再理解

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

练习步骤:

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

//抽象角色:增删改查业务
public interface UserService {
   void add();
   void delete();
   void update();
   void query();
}

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("查询了一个用户");
  }
}

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+"方法");
  }

}

5、测试访问类:

public class Client {
   public static void main(String[] args) {
       //真实业务
       UserServiceImpl userService = new UserServiceImpl();
       //代理类
       UserServiceProxy proxy = new UserServiceProxy();
       //使用代理类实现日志功能!
       proxy.setUserService(userService);

       proxy.add();
  }
}

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

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

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

spring-10

9.3 动态代理

  • 动态代理的角色和静态代理的一样 .
  • 动态代理的代理类是动态生成的 . 静态代理的代理类是我们提前写好的
  • 动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理
    • 基于接口的动态代理----JDK动态代理
    • 基于类的动态代理–cglib
    • 现在用的比较多的是 javasist 来生成动态代理 . 百度一下javasist
    • 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!、

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

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

【InvocationHandler:调用处理程序】

spring-11

Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。

【Proxy : 代理】

spring-12

spring-13

spring-14

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

代码实现

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

Rent . java 即抽象角色

//抽象角色:租房
public interface Rent {
   public void rent();
}

Host . java 即真实角色

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

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("收中介费");
  }

}

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

}

核心:一个动态代理 , 一般代理某一类业务 , 一个动态代理可以代理多个类,代理的是接口!、

9.4 深化理解

我们来使用动态代理实现代理我们后面写的UserService!

我们也可以编写一个通用的动态代理实现的类!所有的代理对象设置为Object即可!

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

   // proxy : 代理类
   // method : 代理类的调用处理程序的方法对象.
   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 methodName){
       System.out.println("执行了"+methodName+"方法");
  }

}

测试!

public class Test {
   public static void main(String[] args) {
       //真实对象
       UserServiceImpl userService = new UserServiceImpl();
       //代理对象的调用处理程序
       ProxyInvocationHandler pih = new ProxyInvocationHandler();
       pih.setTarget(userService); //设置要代理的对象
       UserService proxy = (UserService)pih.getProxy(); //动态生成代理类!
       proxy.delete();
  }
}

测试,增删改查,查看结果!

1、动态代理的好处

静态代理有的它都有,静态代理没有的,它也有!

  • 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
  • 公共的业务由代理来完成 . 实现了业务的分工 ,
  • 公共业务发生扩展时变得更加集中和方便 .
  • 一个动态代理 , 一般代理某一类业务
  • 一个动态代理可以代理多个类,代理的是接口!

10. AOP就这么简单

上一讲中我们讲解了代理模式,这是AOP的基础,一定要先搞懂它

狂神说Spring06:静态/动态代理模式

那我们接下来就来聊聊AOP吧!

10.1 什么是AOP

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

spring-15

Aop在Spring中的作用

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

以下名词需要了解下:

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

spring-16

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

spring-17

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

10.2 使用Spring实现Aop

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

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

第一种方式

通过 Spring API 实现

首先编写我们的业务接口和实现类

public interface UserService {
    public void add();

    public void delete();

    public void update();

    public void query();
}
public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("add");
    }

    @Override
    public void delete() {
        System.out.println("delete");
    }

    @Override
    public void update() {
        System.out.println("update");
    }

    @Override
    public void query() {
        System.out.println("query");
    }
}

然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强

public class Log implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + " 执行了 " + method.getName() + "方法");
    }
}
public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(method.getName() + "方法执行了,返回了" + returnValue);
    }
}

最后去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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:annotation-config/>

    <bean id="userServiceImpl" class="com.LEEZ.service.UserServiceImpl"/>
    <bean id="log" class="com.LEEZ.log.Log"/>
    <bean id="afterLog" class="com.LEEZ.log.AfterLog"/>

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

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

</beans>

测试

public class MyTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口,不是实现类
        UserService userService = context.getBean(UserService.class);
        userService.add();
    }
}

Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .

Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .

第二种方式

自定义类来实现Aop

目标业务类不变依旧是userServiceImpl

第一步 : 写我们自己的一个切入类

public class DiyPointcut {

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

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

    <context:annotation-config/>

    <bean id="userServiceImpl" class="com.LEEZ.service.UserServiceImpl"/>
    <bean id="log" class="com.LEEZ.log.Log"/>
    <bean id="afterLog" class="com.LEEZ.log.AfterLog"/>

    <!--方法一:使用原生Spring api接口-->
    <!--配置aop,需要导入aop的约束-->
<!--    <aop:config>-->
<!--        &lt;!&ndash;切入点:expression 表达式,execution(* * * * *)&ndash;&gt;-->
<!--        <aop:pointcut id="pointcut" expression="execution(* com.LEEZ.service.UserServiceImpl.*(..))"/>-->

<!--        &lt;!&ndash;执行环绕增加&ndash;&gt;-->
<!--        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>-->
<!--        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>-->
<!--    </aop:config>-->

    <!--方法二:自定义接口-->
    <bean id="diy" class="com.LEEZ.Diy.DiyPointCut"/>

    <aop:config>
        <aop:aspect ref="diy">
            <aop:pointcut id="pointcut" expression="execution(* com.LEEZ.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

</beans>

测试:

public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService");
       userService.add();
  }
}

第三种方式

使用注解实现

第一步:编写一个注解实现的增强类

@Aspect
public class AnnotationPointcut {
   @Before("execution(* com.LEEZ.service.UserServiceImpl.*(..))")
   public void before(){
       System.out.println("---------方法执行前---------");
  }

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

   @Around("execution(* com.LEEZ.service.UserServiceImpl.*(..))")
   public void around(ProceedingJoinPoint jp) throws Throwable {
       System.out.println("环绕前");
       System.out.println("签名:"+jp.getSignature());
       //执行目标方法proceed
       Object proceed = jp.proceed();
       System.out.println("环绕后");
       System.out.println(proceed);
  }
}

第二步:在Spring配置文件中,注册bean,并增加支持注解的配置

<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.LEEZ.Diy.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

aop:aspectj-autoproxy:说明

通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了

<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

到了这里,AOP的思想和使用相信大家就没问题了!

11. 整合Mybatis

步骤:

  • 1.导入相关jar包
    • Junit
    • mybatis
    • MySQL
    • spring相关
    • aop织入
    • mybatis-spring 【new】

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SpringStudy</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Spring-01-test</module>
        <module>spring-02-helloSpring</module>
        <module>spring-03-ioc2</module>
        <module>spring-04-di</module>
        <module>spring-05</module>
        <module>spring-06</module>
        <module>spring-07</module>
        <module>spring-08</module>
        <module>spring-09</module>
    </modules>

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

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--spring操作数据库的话,还需要spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>

</project>

maven 静态资源导入问题

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
  • 2.编写配置文件
  • 3.测试

11.1 回忆Mybatis

1.编写实体类

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

2.编写核心配置文件
mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    
    <typeAliases>
        <package name="com.LEEZ.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.LEEZ.mapper.UserMapper"/>
    </mappers>
</configuration>

3.编写接口
UserMapper

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

4.编写Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.LEEZ.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from mybatis.user;
        </select>
</mapper>

5.测试

@Test
public void test() throws IOException {
    String resources = "mybatis-config.xml";
    InputStream in = Resources.getResourceAsStream(resources);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    //true为打开自动提交事务
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = userMapper.selectUser();
    for (User user : users) {
        System.out.println(user);
    }
}

注意点:

  1. 找不到类就是maven资源导出问题 target中没有导出文件
  2. 编写完mapper.xml文件后,一定要去mybatis-config.xml中绑定mapper
  3. 数据库UTC设置 Asia/Shanghai
  4. 工具类放下下面
//sqlSessionFactory -->sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            //使用mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";//注意
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //
    public static SqlSession getSqlSession(){
         return sqlSessionFactory.openSession(true);
    }

}

11.2 Mybatis-spring

方式一

1.编写数据源配置
2.sqlSessionFactory
3.sqlSessionTemplete

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

    <context:annotation-config/>

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
     我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
    </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/LEEZ/mapper/*.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--SqlSessionTemplate这个类没有set方法,但有构造方法,因此通过构造方法注入属性-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

4.给接口添加实现类

public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSessionTemplate;

    //要想通过spring注入属性,必须有set方法
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        return users;
    }
}

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

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

6.测试

@Test
public void test1() {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
    UserMapper userMapper = context.getBean(UserMapper.class);
    List<User> users = userMapper.selectUser();
    for (User user : users) {
        System.out.println(user);
    }
}

注意:

  1. 其实在我的理解里,写实现类就是将之前测试类里的代码分离了出来,但这样的好处在于,可以将各个Mapper写进Spring的容器中,由Spring同一管理

  2. 所以,虽然多了些代码量,但复用管理成本降低了。

  3. 二者的代码区别:

    1. //提取出来作为实现类的测试
      @Test
      public void test1() {
          ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
          UserMapper userMapper = context.getBean(UserMapper.class);
          List<User> users = userMapper.selectUser();
          for (User user : users) {
              System.out.println(user);
          }
      }
      
    2. //没有提取出来作为实现类的测试,仅仅是多了获取sqlSession和mapper的过程
      @Test
      public void test2() {
          ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
          SqlSessionTemplate sqlSessionTemplate = (SqlSessionTemplate) context.getBean("sqlSessionTemplate");
          UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
          List<User> users = mapper.selectUser();
          for (User user : users) {
              System.out.println(user);
          }
      }
      

方式二 SqlSessionDaoSupport

spring-18

spring-dao.xml

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

    <context:annotation-config/>

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
     我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
    </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/LEEZ/mapper/*.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--SqlSessionTemplate这个类没有set方法,但有构造方法,因此通过构造方法注入属性-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.LEEZ.mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    </bean>
</beans>

实现类:UserMapperImpl2

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

将新写的实现类注入到spring-dao.xml

<bean id="userMapper2" class="com.LEEZ.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

测试:

@Test
public void test3() {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
    UserMapperImpl2 userMapper2 = (UserMapperImpl2) context.getBean("userMapper2");
    List<User> users = userMapper2.selectUser();
    for (User user : users) {
        System.out.println(user);
    }
}

12. 声明式事务

12.1 回顾事务

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

事务的ACID原则:

  • 原子性:
    • 事务是原子性操作,要么同时全部完成,要么完全不起作用。
  • 一致性:
    • 一旦所有事务动作完成,事务就要被提交,数据和资源处于一种满足业务规格的一致性状态
    • 事务提交前和提交后,数据的完整性不变
  • 隔离性:
    • 多个事务同时处理相同的数据,每个事务都应该与其他事务隔离开来,防止数据损坏
  • 持久性
    • 事务一旦完成,无论系统发生什么错误,结果都不会收到影响,通常情况下,事务一旦被提交,就会被持久化到数据库中。

测试:

将上面的代码拷贝到一个新项目中
在之前的案例中,我们给userMapper接口新增两个方法,删除和增加用户;

//添加一个用户
int addUser(User user);

//根据id删除用户
int deleteUser(int id);

UserMapper文件,我们故意把 deletes 写错,测试!

<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>

<delete id="deleteUser" parameterType="int">
deletes from user where id = #{id}
</delete>

编写接口的UserMapperImpl实现类,在实现类中,我们去操作一波

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {

    //增加一些操作
    public List<User> selectUser() {
        User user = new User(5, "小王", "185161");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(5);

        return mapper.selectUser();
    }
    
    //新增
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

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

测试

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

    for (User user : userMapper.selectUser()) {
        System.out.println(user);
    }
}

报错:sql异常,delete写错了

结果 :数据库结果显示插入成功!

没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!

以前我们都需要自己手动管理事务,十分麻烦!

但是Spring给我们提供了事务管理,我们只需要配置即可;

13.2、Spring中的事务管理

spring在不同的事务管理API之上定义了一个抽象层,是的开发人员不必了解底层的事务管理API就可以使用spring的事务管理机制。spring支持编程式事务管理和声明式的事务管理

编程式事务管理

  • 将事务管理代码嵌入到业务方法中来控制事务的提交和回滚
  • 缺点:必须在每个事务的操作业务逻辑中包含额外的事务管理代码

声明式事务管理

  • 一般情况下比编程式事务管理好用
  • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理
  • 将事务管理作为横切关注点,通过aop方法模块化。spring中通过spring aop框架支持声明式事务管理

1、使用spring管理实务,注意头文件的约束导入:tx

xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

2、JDBC事务

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

3、配置好事务管理器后,我们需要去配置事务的通知

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

spring事务传播特性:

事务传播行为就是多个事务方法相互调用的时候,事务如何在这些方法间传播。spring支持7中事务传播行为:

  • propagation_requierd:如果没有当前事务,就新建一个事务,如果已存在一个事务中,加入这个事务;
  • propagation_support:支持当前事务,如果没有当前事务,就以非事务方法执行
  • propagation_mandatory:支持当前事务,如果没有当前事务就抛出异常
  • propagation_requierd_new:不支持当前事务,新建事务,如果当前存在任务,就把当前任务挂起。
  • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • propagation_never:以非事务方式执行,如果当前存在事务,就抛出异常
  • propagation_nested:如果当前存在事务,就在嵌套事务内执行,如果当前没有事务,则执行与propagation_required类似的操作。

spring默认的事务传播行为是;propagation_required,它适用于绝大多数的情况。

就好比,我们刚才的几个方法存在调用,所以会被放在一组事务中。

4、配置AOP,导入aop的头文件

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

5、删掉刚才插入的数据,再次测试

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

    for (User user : userMapper.selectUser()) {
        System.out.println(user);
    }
}

思考:

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况;
  • 如果我们不在spring中配置声明式事务,我们就需要在代码中手动配置事务
  • 事务在项目开发中十分重要,涉及到数据的一致性和完整性的问题。

标签:Spring,void,代理,class,学习,spring,println,public
From: https://www.cnblogs.com/leezStudy/p/16945263.html

相关文章

  • SpringBoot
    自动装配原理从Spring的IOC到SpringBoot的自动装配原理DeferedImportSelector对Bean加载顺序的影响(当然是由@Import导入的)  DeferedImportSelector有一个分组的概念......
  • spring mvc环境之监听器、过滤器、拦截器(六)
    1.监听器Servlet的监听器Listener,它是实现了javax.servlet.ServletContextListener接口的服务器端程序,它也是随web应用的启动而启动,只初始化一次,随web应用的停止而销毁。......
  • SpringBoot Maven多模块项目 mapper.xml 文件扫描不到问题
    项目使用的是SpringBoot+MybatisPlus,maven多模块项目,其中有多个模块的resource下面有Mapper.xml文件。这点是问题的前提。。。。。在配置文件里面也指定了mybatis-plus......
  • Springboot 获取 resource 下的文件夹路径的坑
    现在有个需求是需要利用模板文件生成HTML或者PDF文件,然后由于HTML模板文件里面包含图片和字体,然后我就在resource文件夹下新建了一个文件夹,然后又分类,也就是resource......
  • SpringCloud-Feign接口调用超时:feign.RetryableException: Connection timed out (Co
    刚开始代码里面使用的是:@FeignClient("leak")publicinterfaceLeakFeignServiceFeign{在本地跑是正常的,上了测试环境,两个服务独立部署后,出现如下异常:feign.Retryabl......
  • 【SpringCloud】Eureka Server实现高可用(IDEA同时启动两个Eureka Server)
    当你翻到这篇博客,可能你已经搭建好了一个EurekaServer的实例,这里记录一下参考网上的资料搭建实例的时候遇到的坑,视频里这点好像少了,使用IDEA启动两个EurekaServer。如果还......
  • 【Springboot】Json转换工具
    HttpClient请求数据后是json字符串,需要我们自己把Json字符串反序列化为对象,我们会使用JacksonJson工具来实现。JacksonJson是SpringMVC内置的json处理工具,其中有一个Objec......
  • 【Day01】初始Springboot
    初始Springboot:学习目标1.了解SpringBoot1.1.什么是SpringBoot1.2.为什么要学习SpringBoot1.3.SpringBoot的特点2.快速入门2.1.创建工程2.2.添加依赖2.2.1.添......
  • 【问题】Unknown return value type: java.lang.Integer springboot插入数据 报错
    很诡异的事情发生了。。。。。。。在使用springboot搭建一个springboot整合mybatis的demo时,测试插入数据的方法,数据成功插入数据库了,但是控制台却报了这个错,提示为止返回类......
  • 数学基础学习目录
    文章目录​​线性代数​​​​概率论​​​​高数​​2021-10-24!祝大家节日快乐,也希望自己的数学基础开启新的篇章。线性代数​​矩阵的迹相关性质​​正定矩阵和半正定矩阵......