1.1 前言

1.1.1 原生web框架开发存在哪些问题?

  • 传统的web开发存在耦合度较高的问题
  • API复杂,使用效率较低
  • 侵入性强,移植性差

1.2 Spring框架

1.2.1 简介

是什么:是一个优秀的、非侵入的、轻量级JavaEE解决方案的框架
主要特点:IOC(控制反转)、DI(依赖注入)
优秀特性:是众多优秀设计模式的集合(工厂、单例、代理、适配器、包装器、模板、策略、观察者)
俗称:可以和众多框架进行有机整合、称为“胶水粘合剂”

1.2.2 下载地址

官方网站:https://spring.io/

1.2.3 架构组成

  • 核心技术:依赖注入,事件,资源,i18n,验证,数据绑定,类型转换,SpEL,AOP。
  • 测试:模拟对象,TestContext框架,Spring MVC测试,WebTestClient。
  • 数据访问:事务,DAO支持,JDBC,ORM,封送XML。
  • Spring MVC和 Spring WebFlux Web框架。
  • 集成:远程处理,JMS,JCA,JMX,电子邮件,任务,调度,缓存。
  • 语言:Kotlin,Groovy,动态语言。

    1.2.4 架构图

001.png

GroupId ArtifactId 说明
org.springframework spring-beans Beans 支持,包含 Groovy
org.springframework spring-aop 基于代理的AOP支持
org.springframework spring-aspects 基于AspectJ 的切面
org.springframework spring-context 应用上下文运行时,包括调度和远程抽象
org.springframework spring-context-support 支持将常见的第三方类库集成到 Spring 应用上下文
org.springframework spring-core 其他模块所依赖的核心模块
org.springframework spring-expression Spring 表达式语言,SpEL
org.springframework spring-instrument JVM 引导的仪表(监测器)代理
org.springframework spring-instrument-tomcat Tomcat 的仪表(监测器)代理
org.springframework spring-jdbc 支持包括数据源设置和 JDBC 访问支持
org.springframework spring-jms 支持包括发送/接收JMS消息的助手类
org.springframework spring-messaging 对消息架构和协议的支持
org.springframework spring-orm 对象/关系映射,包括对 JPA 和 Hibernate 的支持
org.springframework spring-oxm 对象/XML 映射(Object/XML Mapping,OXM)
org.springframework spring-test 单元测试和集成测试支持组件
org.springframework spring-tx 事务基础组件,包括对 DAO 的支持及 JCA 的集成
org.springframework spring-web web支持包,包括客户端及web远程调用
org.springframework spring-webmvc REST web 服务及 web 应用的 MVC 实现
org.springframework spring-webmvc-portlet 用于 Portlet 环境的MVC实现
org.springframework spring-websocket WebSocket 和 SockJS 实现,包括对 STOMP 的支持
org.springframework spring-jcl Jakarta Commons Logging 日志系统

1.3 Spring环境搭建

1.3.1 pom.xml引入Spring常用依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation=
  5. "http://maven.apache.org/POM/4.0.0
  6. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  7. <modelVersion>4.0.0</modelVersion>
  8. <groupId>com.qf</groupId>
  9. <artifactId>hello-spring</artifactId>
  10. <version>1.0-SNAPSHOT</version>
  11. <dependencies>
  12. <!-- Spring常用依赖 -->
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-context</artifactId>
  16. <version>5.1.6.RELEASE</version>
  17. </dependency>
  18. </dependencies>
  19. </project>

1.3.2 创建Spring配置文件

  • 可以自定义命名 ```java <?xml version=”1.0” encoding=”UTF-8”?>

<a name="AJAbD"></a>
### 1.4 依赖与配置文件详解
<a name="blylP"></a>
#### 1.4.1 相关简介
Spring框架包含多个模块,每个模块各司其职
<a name="JUrY7"></a>
#### 1.4.2 Spring依赖关系
![image-20191230164455973.png](https://cdn.nlark.com/yuque/0/2020/png/1319194/1593526984454-ebf07f38-8ef5-4ef1-a7d8-5a1e1026fc28.png#align=left&display=inline&height=254&margin=%5Bobject%20Object%5D&name=image-20191230164455973.png&originHeight=254&originWidth=558&size=23473&status=done&style=none&width=558)

- [注意:Jar包彼此存在依赖,只需引入最外层Jar即可由Maven自动将相关依赖Jar引入到项目中。]()
<a name="jMYHX"></a>
#### 1.4.3 配置文件相关信息
配置文件中的顶级标签中包含了语义化标签的相关信息
> - xmlns:语义化标签所在的命名空间。
> - xmlns:xsi:XMLSchema-instance 标签遵循Schema标签标准。
> - xsi:schemaLocation:xsd文件位置,用以描述标签语义、属性、取值范围等。

<a name="MlZxu"></a>
#### 1.4.4 Spring工厂结构图
![image.png](https://cdn.nlark.com/yuque/0/2020/png/1319194/1593527590437-92871ee3-568a-403e-bd7e-5ed88c08a13f.png#align=left&display=inline&height=373&margin=%5Bobject%20Object%5D&name=image.png&originHeight=373&originWidth=500&size=86597&status=done&style=none&width=500)<br />![image.png](https://cdn.nlark.com/yuque/0/2020/png/1319194/1593527573392-5de74c67-1a87-433a-9e40-57f1420ed3ff.png#align=left&display=inline&height=491&margin=%5Bobject%20Object%5D&name=image.png&originHeight=491&originWidth=599&size=75256&status=done&style=none&width=599)
<a name="4UkxE"></a>
#### 1.4.5BeanFactory 和 ApplicationContext 的区别

1. BeanFactory 才是 Spring 容器中的顶层接口。
1. ApplicationContext 是它的子接口。
1. BeanFactory 和 ApplicationContext 的区别:
1. 创建对象的时间点不一样。
   1. ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
   - BeanFactory:什么使用什么时候创建对象。
<a name="gUYfN"></a>
### 1.5 IOC(Inversion of Control)控制反转
<a name="kDEyK"></a>
#### 1.5.1 Spring IOC 容器

- springIOC的基础:org.springframework.beans和org.springframework.context的包
- BeanFactory提供了一个配置机制,能够管理任何类
- 在spring中BeanFactory提供configuration framework(配置框架)的基本本功能。
- IOC管理的一个对象称为一个Bean
- 一个对象实例由容器进行实例化,组装管理
<a name="KCYMD"></a>
#### 1.5.2 容器概述

- org.springframework.context.ApplicationContext接口表示IOC容器
   - 负责实例化,配置Bean节点   
- spring提供了ApplicationContext接口的几个实现类
- 通常创建 ClassPathXmlApplicationContext 或 FileSystemXmlApplicationContext 实例
- 来读取想读取XML配置声明<br />
<a name="bGxJp"></a>
#### 1.5.3 配置元数据

- XML预算内数据的基本结构:
```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="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

id属性是一个String,用来标识单个bean节点, class属性定义bean的类型并且使用完全限定的类名

1.5.4 实例化容器

  • 实例化IOC容器:提供给ApplicationContent构造函数的位置路径,实际上是资源strings,它允许外部资源加载configuration(配置)元数据

    ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
    
  • services.xml配置文件的实例: ```xml <?xml version=”1.0” encoding=”UTF-8”?>


- 以下是daos.xml文件
```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="accountDao"
        class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for data access objects go here -->

</beans>
  • 使用另一个文件中的Bean节点元素

    <beans>
      <import resource="services.xml"/>
      <import resource="resources/messageSource.xml"/>
      <import resource="/resources/themeSource.xml"/>
    
      <bean id="bean1" class="..."/>
      <bean id="bean2" class="..."/>
    </beans>
    

    使用”../“相对路径是可以的,但不建议这样做,这样与其他文件产生了依赖

1.5.5Groovy Bean 定义 DSL

作为外部化配置元数据的进一步示例,bean 定义也可以在 Spring 的 Groovy Bean Definition DSL 中表示,如 Grails framework 中所知。通常,此类 configuration 将存在于“.groovy”文件中,其结构如下所示:

beans {
    dataSource(BasicDataSource) {
        driverClassName = "org.hsqldb.jdbcDriver"
        url = "jdbc:hsqldb:mem:grailsDB"
        username = "sa"
        password = ""
        settings = [mynew:"setting"]
    }
    sessionFactory(SessionFactory) {
        dataSource = dataSource
    }
    myService(MyService) {
        nestedBean = { AnotherBean bean ->
            dataSource = dataSource
        }
    }
}

1.5.6 使用容器

  • ApplicationContext是一个高级工厂接口
  • 能够维护不同不同的注册表和beans
  • 提供的API:
    • T getBean(String name,Class requiredType)
    • 可以检索bean节点的实例 ```java // create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext(“services.xml”, “daos.xml”);

// retrieve configured instance PetStoreService service = context.getBean(“petStore”, PetStoreService.class);

// use configured instance List userList = service.getUsernameList();


- 读取Groovy configuration
```java
ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");

1.5.7 Bean概述

  • 可以控制管理多个beans
  • 配置文件格式:定义形式
    • 全限定包类名:通常是bean具体类指定
    • 依赖关系
  • 命名:id必须唯一
  • 定义外别名
    <alias name="fromName" alias="toName"/>
    

    name必须与bean的name保持一致

1.5.8 Scope作用域(控制单例模式或者多例模式)

  • 配置

    <!--
      singleton(默认):每次调用工厂,得到的都是同一个对象。
      prototype:每次调用工厂,都会创建新的对象。
    -->
    <bean id="mc" class="com.qf.zcg.spring.day1.t1.basic.MyClass" scope="singleton" />
    

    1.5.9 实例化beans

  • 本质上是创建一个或者多个对象

  • 创建bean对象的实质:
    • 通常在容器本身是通过反射调
    • 用构造参数来创建bean
    • 尽量创建更少的对象情况下
  • 使用构造参数实例化
    • 只需要提供class
    • 给相应的构造参数
  • 使用工厂方法进行实例化

1.6 依赖关系

1.6.1 DI依赖注入

含义:根据容器依赖关系,由容器进行将对象或者值注入到属性中去

1.6.2 DI分类

  • Constructor-based依赖注入
  • Setter-based依赖注入

    1.6.3 构造器注入

  • 具有其他类的依赖项时: ```java package x.y;

public class Foo {

public Foo(Bar bar, Baz baz) {
    // ...
}

}

```xml
<beans>
    <bean id="foo" class="x.y.Foo">
        <constructor-arg ref="bar"/>
        <constructor-arg ref="baz"/>
    </bean>

    <bean id="bar" class="x.y.Bar"/>

    <bean id="baz" class="x.y.Baz"/>
</beans>
  • 当类型已知时: ```java package examples;

public class ExampleBean {

// Number of years to calculate the Ultimate Answer
private int years;

// The Answer to Life, the Universe, and Everything
private String ultimateAnswer;

public ExampleBean(int years, String ultimateAnswer) {
    this.years = years;
    this.ultimateAnswer = ultimateAnswer;
}

}


- 根据参数类型:进行注入
```xml
<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>
  • 根据构造参数的索引进行注入

    <bean id="exampleBean" class="examples.ExampleBean">
      <constructor-arg index="0" value="7500000"/>
      <constructor-arg index="1" value="42"/>
    </bean>
    
  • 可以会根据参数的名字进行注入

    <bean id="exampleBean" class="examples.ExampleBean">
      <constructor-arg name="years" value="7500000"/>
      <constructor-arg name="ultimateAnswer" value="42"/>
    </bean>
    
  • 可以指定你构造参数名字可以注入 ```java package examples;

public class ExampleBean {

// Fields omitted

@ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
    this.years = years;
    this.ultimateAnswer = ultimateAnswer;
}

}

<a name="AoC3A"></a>
#### 1.6.4 Setter-base依赖注入

- 必须提供相应的get和set方法
```java
public class User {
    private Integer id;
    private String password;
    private String sex;
    private Integer age;
    private Date bornDate;
    private String[] hobbys;
    private Set<String> phones;
    private List<String> names;
    private Map<String,String> countries;
    private Properties files;
    //Getters And Setters
}
bean id="u1" class="com.qf.spring.part1.injection.User">
    <!--base field-->
    <property name="id" value="1001" />
    <property name="password" value="123456" />
    <property name="sex" value="male" />
    <property name="age" value="20" />
    <property name="bornDate" value="1990/1/1" /><!--注意格式"/"-->
</bean>
  • 数组注入

    <bean id="u1" class="com.qf.spring.part1.injection.User">    
      <!--Array-->
      <property name="hobbys">
          <array>
              <value>Run</value>
              <value>Swim</value>
              <value>Climb</value>
          </array>
      </property>
    
      <!--Set-->
      <property name="phones">
          <set>
              <value>13777777777</value>
              <value>13888888888</value>
              <value>13999999999</value>
          </set>
      </property>
    
      <!--List-->
      <property name="names">
          <list>
              <value>tom</value>
              <value>jack</value>
              <value>marry</value>
          </list>
      </property>
    
      <!--Map-->
      <property name="countries">
          <map>
              <entry key="CN" value="China" />
              <entry key="US" value="America" />
              <entry key="KR" value="Korea" />
          </map>
      </property>
    
      <!--Properties-->
      <property name="files">
          <props>
              <prop key="first">One</prop>
              <prop key="second">Two</prop>
              <prop key="third">Three</prop>
          </props>
      </property>
    </bean>
    

    1.6.5 自动注入

    public class UserServiceImpl implements UserService {
      private UserDAO userDAO;
      //Getters And Setters
      ....
    }
    
  • 根据属性类型注入

    <bean id="userDao" class="com.qf.spring.part1.injection.UserDaoImpl" />
    <!-- 为UserServiceImpl中的属性基于类型自动注入值 -->
    <bean id="userService" class="com.qf.spring.part1.injection.UserServiceImpl" autowire="byType"></bean>
    
  • 根据属性名称自动注入

    bean id="userDao" class="com.qf.spring.part1.injection.UserDaoImpl" />
    <!-- 为UserServiceImpl中的属性基于类型自动注入值 -->
    <bean id="userService" class="com.qf.spring.part1.injection.UserServiceImpl" autowire="byName"></bean>
    
  • p命名空间约束注入 ```java

<a name="026YO"></a>
### 1.7 Spring工厂特性
<a name="I7V8z"></a>
#### 1.7.1 饿汉模式

- 工厂创建之后,会将Spring配置文件中创建完成
- 配置bean节点,读取xml文件就会创建对象,默认是单例模式,看Scope作用域
- 优点:
   - 提高程序的运行效率
   - 避免多次IO,减少对象创建时间

<a name="srZ2B"></a>
#### 1.7.2 生命周期的API

- 初始化:“init-method”属性:
   - 对象创建之后,调用此方法
- 摧毁:“destory-method” 属性:
   - 销毁对象调用此方法
   - 分类
      - 单例:Singleton对象由Spring容器
      - 多例:由JVM摧毁
<a name="3ON9t"></a>
#### 1.7.3 生命周期注解
```java
@PostConstruct:表示初始化
@PreDestroy:表示摧毁

1.7.4 不同对象的生命周期

  1. 单例bean:singleton
    1. 工厂创建
    2. 构造方法
    3. set方法(注入值)
    4. init(初始化)
    5. 构建完成
    6. 随着工厂的关闭而摧毁
  2. 多例bean:prototype
    1. 使用创建
    2. 构造方法
    3. set注入
    4. init初始化
    5. 构建完成
    6. 由JVM垃圾回收摧毁

      1.7.5 静态工厂方法方式

  • 静态工厂是什么:
    • 本身不需要实例化
    • 提供静态API创建对象
  • 由工厂通过反射来创建对应对象

1.8 代理

1.8.1 概念

  • 对于核心功能和辅助功能进行分离
  • 实现中间类来对于目标类的管理
  • 通俗理解:
    • 可以在不改变代码的情况下实现相应功能增强

三、Spring框架 - 图2

1.8.2 静态代理设计模式

  • 为每个类添加对应一个代理对象的实现列
  • 可以为该对象添加辅助功能
  • 一个类实现对应对象的的接口实现代理

  • 抽象角色

    /**
    2  * 抽象角色:以租房为例,这是一个租房子的接口
    3  */
    4 public interface Rent {
    5     void rent();
    6 }
    
  • 被代理的角色

    public class Host implements Rent{
    9     public void rent(){
    10         System.out.println("房屋出租");
    11     }
    12 }
    
  • 代理角色

    public class Proxy implements Rent {
    5     private Host host;
    6 
    7     public Proxy() {
    8     }
    9 
    10     public Proxy(Host host) {
    11         this.host = host;
    12     }
    13 
    14     public void setHost(Host host) {
    15         this.host = host;
    16     }
    17 
    18     public void rent() {
    19         seeHouse();
    20         host.rent();
    21         fee();
    22     }
    23 
    24 
    25     //**************代理角色附带(增强)的一些功能**************//
    26     private void seeHouse(){
    27         System.out.println("带租客看房子");
    28     }
    29     private void fee(){
    30         System.out.println("收取中介费");
    31     }
    32 }
    
  • 缺点:

    • 代理类的数量过多,不利于项目管理
    • 很多被代理对象就会对应很多代理对象,这样极就不利于维护

      1.8.3 JDK的动态代理设计模式

  • 创建一个代理类

  • 通过反射实现对于被代理对象的代理
  • 都基于一个基于
  • 主要是都是实现同一个接口
  • 创建一个用户接口 ```java

public interface UserManager { //新增用户抽象方法 void addUser(String userName,String password); //删除用户抽象方法 void delUser(String userName); }


- 创建用户实现类
```java
public class UserManagerImpl implements UserManager{
    //重写新增用户方法
    @Override
    public void addUser(String userName, String password) {
        System.out.println("调用了新增的方法!");
        System.out.println("传入参数为 userName: "+userName+",password: "+password);
    }
    //重写删除用户方法
    @Override
    public void delUser(String userName) {
        System.out.println("调用了删除的方法!");
        System.out.println("传入参数为 userName: "+userName);
    }

}
  • jdk实现代理

    public class JdkProxy implements InvocationHandler {
    private Object target;
    
    public JdkProxy(Object target) {
      this.target = target;
    }
    
    //定义获取代理对象方法
      private Object getJDKProxy(Object targetObject){
          //为目标对象target赋值
          this.target = targetObject;
          //JDK动态代理只能针对实现了接口的类进行代理,newProxyInstance 函数所需参数就可看出,
          //interfaces参数是该动态类所继承的所有接口
          return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
      }
    
    @Override
    public Object invoke(Object proxy, Method method,       Object[] args) throws Throwable {
      System.out.println("before proxy!");
      Object result = method.invoke(source, args);
      System.out.println("after proxy!");
      return result;
    }
    }
    
    public class Client {
    
    @Test
    public void testDynamicProxy() {
      //实例化JDKProxy对象
      JdkProxy jdkProxy = new JdkProxy();
      //获取代理对象
      UserManager proxy = (UserManager) jdkProxy.getJDKProxy(new UserManagerImpl());
      proxy.addUser("Leemus", "MShan");
    }
    }
    
  • 意义:

    • 解决了静态代码维护的困难
    • 通过反射创建对应的代理对象
  • 缺点:

    • 效率较静态代理稍微低,因为必须通过反射来来创建代理对象
    • 这样需要将对应类加载到运行时数据区,所以效率较低
    • 有一定的局限性:
      • 必须要实现同一个接口

        1.8.4 Cglib代理

  • 是什么:

    • 是一个强大代理模式
    • 解决静态代理模式创建多个代理类的问题
    • 还解决了jdk代理需要实现同一个接口的问题
    • 它是基于横切子类的方式实现代理对象的创建
    • 如果代理类是final的类型,不能被重写
  • 具体实现:

    /**
    * 被代理类
    */
    public class Source {
    public void SourceMethod() {
      System.out.println("without implement any interface!");
    }
    }
    
    /**
    * 代理类
    */
    public class SafetyCheckCallback implements MethodInterceptor {
      private Object target;//需要代理的目标对象
    
      @Override
      public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
          System.out.println("before proxy!");
          Object result = methodProxy.invokeSuper(o, objects);
          System.out.println("after proxy!");
          return result;
        }
    
      //定义获取代理对象方法
      public Object getCglibProxy(Object objectTarget){
          //为目标对象target赋值
          this.target = objectTarget;
          Enhancer enhancer = new Enhancer();
          //设置父类,因为Cglib是针对指定的类生成一个子类,所以需要指定父类
          enhancer.setSuperclass(objectTarget.getClass());
          enhancer.setCallback(this);// 设置回调 
          Object result = enhancer.create();//创建并返回代理对象
          return result;
      }
    }
    
    public class Client {
    @Test
    public void testCglibProxy() {
      //实例化CglibProxy对象
      CglibProxy cglib = new CglibProxy();
      //获取代理对象
      UserManager user =  (UserManager) cglib.getCglibProxy(new UserManagerImpl());
      user.delUser("Leemus");
    }
    }
    

    1.9 面向切面编程(AOP)

    1.9.1 概念

  • 全称:AOP(Aspect Oriented Programming)

  • 含义:面向切面编程
    • (Aspect)切面:切入点和通知的结合
  • 目的:

    • 将共同的业务模块封装同一各类中
    • 实现代码复用,减少重复代码
    • 降低模块之间的耦合度
    • 便于维护

      1.9.2 开发术语

  • 连接点(JoinPoint):

    • 可被Spring拦截的点。在spring中,这些点是方法,因为spring只支持方法类型的连接点。
  • 切入点(Pointcut):
    • 所谓的切入点对哪些joinPoint进行拦截的定义
  • 通知(Advice):
    • 给对切入的功能,或者方法
  • 织入(Weaving):
    • 创建动态代理的过程
    • 将通知增强到目标对象的过程
  • 切面(Aspect):

    • 是切入点和通知的结合

      1.9.3 SpringAOP实现原理

      AOP编程是通过动态代理的情的原理对于原始的类的方法添加辅助功能

      1.9.4 环境搭建

  • 引入AOP相关依赖

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.1.6.RELEASE</version>
    </dependency>
    
  • spring的xml文件中引入AOP命名空间

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:context="http://www.springframework.org/schema/context"
         xmlns:aop="http://www.springframework.org/schema/aop"
         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
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         ">
    </beans>
    

    1.9.5 开发细节

  • 基于注解 ```java package com.project.lj.aspectj;

import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component;

@Component @Aspect public class LoggerAspectj { Logger logger =LogManager.getLogger(LoggerAspectj.class); @Pointcut(“execution(boolean com.project.lj.service..(..))”) public void qrd(){} @Before(“qrd()”) public void beforeInfo(JoinPoint joinPoint){ logger.error(“这是一个前置通知,记录的类名和方法名称如下”+joinPoint.getSignature()+”:”+joinPoint.getTarget()); } }

> Aspect表示一个切面
> Poinicut表示一个切入点
> Before():表示一个通知:
> 前置通知:MethodBeforeAdvice<br />        后置通知:AfterAdvice
> 最终通知:AfterReturningAdvice //
> 异常通知:ThrowsAdvice
> 环绕通知:MethodInterceptor

配置文件配置:
```java
  <ano:aspectj-autoproxy></ano:aspectj-autoproxy>
  • 基于XML的配置形式: ```java package com.qf.aaron.aop.basic;

public interface UserService { public void save(); }

```java
package com.qf.aaron.aop.basic;

public class UserServiceImpl implements UserService {
    public void save() {
        System.out.println("save method executed...");
    }
}
package com.qf.aaron.aop.basic;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class MyAdvice implements MethodBeforeAdvice { //实现前置通知接口
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("before advice executed...");
    }
}
<!--原始对象-->
<bean id="us" class="com.qf.aaron.aop.basic.UserServiceImpl" />

<!--辅助对象-->
<bean id="myAdvice" class="com.qf.aaron.aop.basic.MyAdvice" />
<aop:config>
    <!--切点-->
    <aop:pointcut id="myPointCut" expression="execution(* save())" />
</aop:config>
<aop:config>
    <!--组装切面 -->
    <aop:advisor advice-ref="myAdvice" pointcut-ref="myPointCut" />
</aop:config>

1.10 Spring+Mybatis整合

1.10.1 配置数据源

  • 将数组配置到项目中

    1.10.2 引入jdbc.properties配置文件

    #jdbc.properties
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=123456
    

    1.10.3 整合Spring配置文件和properties配置文件

    <!--spring-context.xml-->
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:context="http://www.springframework.org/schema/context"
         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
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         ">
    
      <!--配置文件参数化(参数占位符)-->
      <context:property-placeholder location="classpath:jdbc.properties" />
    
      <!--与PooledDataSource集成(二选一)-->
      <bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
          <property name="driver" value="${driverClass}"/>
          <property name="url" value="${url}"/>
          <property name="username" value="${username}"/>
          <property name="password" value="${password}"/>
      </bean>
    
      <!--与DruidDataSource集成(二选一)-->
      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
          <!--基本配置-->
          <property name="driverClassName" value="${jdbc.driverClass}"/>
          <property name="url" value="${jdbc.url}"/>
          <property name="username" value="${jdbc.username}"/>
          <property name="password" value="${jdbc.password}"/>
      </bean>
    </bean>
    

    1.10.4 Druid

    <!--web.xml-->
    <servlet>
      <servlet-name>DruidStatView</servlet-name>
      <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>DruidStatView</servlet-name>
      <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>
    

    1.11 事务

    1.11.1 事务的属性

    事务的隔离级别

名称 描述
default (默认值)(采用数据库的默认的设置) (建议)
read-uncommited 读未提交
read-commited 读提交 (Oracle数据库默认的隔离级别)
repeatable-read 可重复读 (MySQL数据库默认的隔离级别)
serialized-read 序列化读

隔离级别由低到高为:read-uncommited < read-commited < repeatable-read < serialized-read

1.11.2 并发问题

问题 描述
脏读 一个事务读取到另一个事务还未提交的数据。大于等于 read-commited 可防止
不可重复读 一个事务内多次读取一行数据的相同内容,其结果不一致。大于等于 repeatable-read 可防止
幻影读 一个事务内多次读取一张表中的相同内容,其结果不一致。serialized-read 可防止

1.11.3 事务的传播行为

propagation传播行为

当涉及到事务嵌套(Service调用Service)时,可以设置:

  • SUPPORTS = 不存在外部事务,则不开启新事务;存在外部事务,则合并到外部事务中。(适合查询)
  • REQUIRED = 不存在外部事务,则开启新事务;存在外部事务,则合并到外部事务中。 (默认值)(适合增删改)

1.11.4 事务超时

timeout事务超时时间

当前事务所需操作的数据被其他事务占用,则等待。

  • 100:自定义等待时间100(秒)。
  • -1:由数据库指定等待时间,默认值。(建议)

1.11.5 事务回滚

rollback-for 回滚属性

  • 如果事务中抛出 RuntimeException,则自动回滚
  • 如果事务中抛出 CheckException(非运行时异常 Exception),不会自动回滚,而是默认提交事务
  • 处理方案 : 将CheckException转换成RuntimException上抛,或 设置 rollback-for=”Exception”

1.11.6 编织

<aop:config>
    <aop:pointcut expression="execution(* com.qf.spring.service.UserServiceImpl.*(..))" id="pc"/>
    <!-- 组织切面 -->
    <aop:advisor advice-ref="txManager" pointcut-ref="pc"/>
</aop:config>