spring 笔记

一、spring概述

1.1 spring介绍

spring是一个轻量级的控制反转和面向切面的容器框架,用来解决企业项目开发的复杂度问题---解耦

  • 轻量级:体积小,对代码没有侵入性
  • 控制反转:IOC inverse of control, 把创建对象的工作交由spring完成,spring在创建对象的同时可以完成对象属性的赋值(DI)
  • 面向切面:AOP aspect oriented programming 面向切面编程,可以在不改变原有业务逻辑的情况下实现对业务的增强
  • 容器:实例的容器,管理创建的对象

1.2 spring架构简介

image-20220802084037659

1.2.1 core container

spring的容器组件,用于完成实例的创建和管理

  • core 容器组件的核心
  • beans 实例对象的管理
  • context 容器上下文

1.2.2 AOP Aspects

spring的AOP组件,实现面向切面编程

  • aop 
  • aspects

1.2.3 WEB

Spring web组件,实际指的是springMVC框架,实现web项目的MVC控制

  • web ---spring 对web项目的支持
  • webmvc --- springMVC

1.2.4 Data Access 

spring 数据访问组件,也是一个基于JDBC封装的持久层框架(即使没有mybatis,spring也可以完成持久化操作)

  • transactions  事务管理

1.2.5 test

spring的单元测试组件,提供了spring环境下的单元测试支持。

二、Spring IOC --- 基于XML

spring ioc 容器组件,可以完成对象的创建,对象属性赋值,对象的管理

2.1 spring框架部署(IOC相关)

  1. 创建maven工程
  2. 添加springIOC依赖
    1. core
    2. beans
    3. context --- 其实只导入这一个就行了,因为其他的依赖也会一起导入
  3. 创建spring配置文件
    1. 配置文件来“告诉”spring容器创建什么对象,给对象属性怎么赋值
    2. resources目录下创建名为applicationContext.xml文件(文件名可以自定义,需要定义一些规则,可以创建一个模板)
spring 依赖
<!--
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-beans</artifactId>
	<version>5.2.10.RELEASE</version>
</dependency>
-->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.2.10.RELEASE</version>
</dependency>

2.2 springIOC的使用 :创建并管理对象

  1. 创建do实体类,如Student类
  2. applicationContext.xml文件中配置bean标签
  3. 初始化spring容器,加载spring配置文件,获取实例对象
只完成实例的创建,但是属性没有值
<bean id="studentDo唯一标识" name="dao" class="Student的全限定名"/>

完成实例的创建,同时给name属性赋值
<bean id="studentDo唯一标识" name="dao" class="Student的全限定名">
	<property name="stuName" value="zhangsan" />
</bean>

public static void main(String[] args) {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
	//此处根据bean标签的id属性和name属性的任意一个值来获取bean对象
    // 创建出来student对象,但是属性没有值
	Student Student1 = (Student) ctx.getBean("studentDo"); 
}

2.3 IOC和DI 

  • IOC inverse of control控制反转,当我们需要通过spring完成对象的创建时,需要将这个类交给spring进行管理 ---- 通过配置bean标签,spring反射
  • DI dependency injection 依赖注入,通过spring容器,给创建的对象属性赋值

2.4 DI 

2.4.1 依赖注入的方式 --- 反射

spring容器加载配置文件后,通过反射创建类的对象,并给属性赋值。通过反射实现属性注入有以下几种方式:

  • set方法注入
  • 构造器注入
  • 接口注入(不常用。。。)

2.4.2 set注入

在bean标签中通过配置property标签给属性赋值,实际就是通过set方法进行注入

  • 简单类型及字符串 ----> 直接通过property标签的value属性进行赋值
  • 引用类型   
    • ----> 使用property标签ref属性注入引用类型对象
    • ----> 在property标签里面创建bean标签
  • 集合类型
    • list 
      • list<简单类型封装类或者字符串>, 可以在property 的value里面直接赋值 逗号隔开
      • list<引用类型>  见下面
    • set ---和list一样,就是把list标签变成set
    • map
<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl">
	<property name="bookDao" ref="bookDao"/>
</bean>
<bean id="bookDao" class="com.itheima.dao.imipl.BookDaoImpl"/>

-------

<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl">
	<property name="bookDao">
		<bean id="bookDao" class="com.itheima.dao.imipl.BookDaoImpl"/>
	</property>
</bean>

--------
list 依赖注入1
<property name="hobbies" value="唱,跳,rap">

---------
list 依赖注入2
<property name="hobbies">
	<list>
		<value>唱</value>
		<value>跳</value>
		<value>rap</value>
	</list>
</property>

---------
list 依赖注入3

<property name="hobbies">
	<list>
		<bean id="book" class="com.itheima.Book"/>
		<bean id="book" class="com.itheima.Book"/>
		<bean id="book" class="com.itheima.Book"/>
	</list>
</property>

---------
list 依赖注入4

<property name="hobbies">
	<list>
		<ref id="book"/>
		<ref id="book"/>
	</list>
</property>

<bean id="book" class="com.itheima.Book"/>

---------
map

<property name="card">
	<map>
		<entry  key="身份证" value="123712739171293"></entry>
		<entry  key="银行卡" value="234234234324344"></entry>
	</map>
</property>

2.4.3 构造器注入

  • 简单类型和字符串
    • 1、定义有参构造器,2、使用constructor-arg标签,index值为第几个参数,value为要注入的值
  • 对象类型
  • 集合类型
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
	<constructor-arg name="databaseName" index="0" value="mysql"/>
	<constructor-arg name="connectionNum" index="1" value="666"/>
</bean>

<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl">
	<constructor-arg name="bookDao" ref="bookDao"/>
	<constructor-arg name="userDao" ref="userDao"/>
</bean>

2.5 ioc- bean的作用域

同一个bean_id ,通过配置scope 的值来指定对象的作用域

  • singleton ---单例模式  默认的值,默认饿汉模式,初始化阶段就会完成实例的创建
  • prototype ---多例模式
<bean id="book" class="book的全限定名" scope="" lazy-init=""/>
scope 有两个取值
singleton ---单例模式  默认的
prototype ---多例模式

lazy-init默认取值false,饿汉模式,设置为true可以改为懒汉模式

2.6 bean 的生命周期

bean标签中可以

  • 通过init-method属性指定当前bean的初始化方法,在构造器执行之后执行
  • 通过destroy-method指定当前bean的销毁方法,在对象销毁之前执行

2.7 自动装配

spring在实例化当前bean时,重spring自己的容器中找到匹配的实例赋值给当前bean的属性,通过bean标签中的autowire进行配置

  • byName:根据当前bean的属性名, 在spring容器中寻找名称匹配的对象(bean中的属性名称和spring容器中其他bean的id 进行比较,有可能导致类型不一致)
  • byType:根据当前bean的属性类型,在spring容器中寻找类型匹配的对象 (要是配置了两个不同id的bean,也会报错)

2.8 ioc的工作原理

三、Spring IOC --- 基于注解

3.1 spring框架部署

3.1.1 创建maven项目

3.1.2添加springIOC依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.13.RELEASE</version>
</dependency>

3.1.3 创建spring配置文件,声明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"
       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/>

    <!-- 声明Spring工厂注解的扫描范围 -->
    <context:component-scan base-package="com.qfedu.beans"/>

</beans>

3.2 IOC的常见注解

3.2.1 @Component

  • 类注解,声明此类被spring容器进行管理,相当于bean标签
  • @Component(value=“stu”)value属性的值相当于bean标签中的id,可以省略,如果省略则当前类的id默认为类名首字母改小写
  • 除了@Component, @Service、@Controller、@Repository这三个注解也可以将类声明给Spring管理,他们主要是语义上的区别
    • @Controller 注解主要声明将控制器类配置给Spring管理,例如Servlet
    • @Service 注解主要声明业务处理类配置Spring管理,Service接口的实现类
    • @Repository 直接主要声明持久化类配置给Spring管理,DAO接口

3.2.2 @Scope

  • 类注解,用于声明当前类是否是单例模式,相当于bean标签的scope属性
  • @Scope("prototype") 表示声明当前类为非单例模式(默认单例模式)

3.2.3 @Lazy

  • 类注解,用于声明一个单例bean,是否为懒汉模式
  • 默认为饿汉模式,@Lazy(true) 表示声明为懒汉模式

3.2.4 @PostConstruct

  • 方法注解,声明一个方法为当前类的初始化方法(在构造器之后执行),相当于bean标签的init-method属性

3.2.5 @PreDestory

  • 方法注解,声明一个方法为当前类的销毁方法(在对象从容器中释放之前执行),相当于bean标签的destory-method属性

3.2.6 @Autowoired

  • 属性注解,声明当前属性自动装配,默认为byType
  • @Autowired(required = false) 通过requried属性设置当前自动装配是否为必须(默认必须——如果没有找到类型与属性类型匹配的bean则抛出异常)
// 也可以用在set方法上,ref引用,@Qualifier来byName寻找
@Autowired
public void setClazz(@Qualifier("c2") Clazz clazz) {
    this.clazz = clazz;
}

3.2.7 @Resource

  • 属性注解,也用于声明属性自动装配

  • 默认装配方式为byName,如果根据byName没有找到对应的bean,则继续根据byType寻找对应的bean,根据byType如果依然没有找到Bean或者找到不止一个类型匹配的bean,则抛出异常。

四,动态代理

代理设计模式的优点:将通用性的工作都交给代理对象完成,被代理对象只需专注自己的核心业务。

动态代理,几乎可以为所有的类产生代理对象

4.1 JDK动态代理类实现

JDK动态代理是通过被代理类实现的接口来创建代理对象的,因此JDK动态代理只能代理实现了接口的类的对象。没有实现接口的类是不能用这种方式产生代理对象。

//使用代理对象调用方法,并不会执行调用的方法,
//而是进入到创建代理对象时指定的InvocationHandler类种的invoke方法,调用的方法作为一个Method参数,传递给了invoke方法

/***
 * JDK动态代理:是通过被代理对象实现的接口产生其代理对象的
 * 1.创建一个类,实现InvocationHandler接口,重写invoke方法
 * 2.在类种定义一个Object类型的变量,并提供这个变量的有参构造器,用于将被代理对象传递进来
 * 3.定义getProxy方法,用于创建并返回代理对象
 */
public class JDKDynamicProxy implements InvocationHandler {
    //被代理对象
    private Object obj;
    public JDKDynamicProxy(Object obj) {
        this.obj = obj;
    }
    //产生代理对象,返回代理对象
    public Object getProxy(){
        //1.获取被代理对象的类加载器
        ClassLoader classLoader = obj.getClass().getClassLoader();
        //2.获取被代理对象的类实现的接口
        Class<?>[] interfaces = obj.getClass().getInterfaces();
        //3.产生代理对象(通过被代理对象的类加载器及实现的接口)
        //第一个参数:被代理对象的类加载器
        //第二个参数:被代理对象实现的接口
        //第三个参数:使用产生代理对象调用方法时,用于拦截方法执行的处理器
        Object proxy = Proxy.newProxyInstance(classLoader, interfaces,this);
        return proxy;
    }

    // 代理对象调用代理方法时,JDK就会帮你调用这个invoke方法。
    // 这个方法是jdk调用的,因此这三个参数jdk会自动传入
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        begin();
        Object returnValue = method.invoke(obj,args);  //执行method方法(insert)
        commit();

        // 注意要将目标方法的返回值返回
        return returnValue;
    }

    public void begin(){
        System.out.println("----------开启事务");
    }

    public void commit(){
        System.out.println("----------提交事务");
    }
}

// --------------测试------------------

 //创建被代理对象
BookDAOImpl bookDAO = new BookDAOImpl();
StudentDAOImpl studentDAO = new StudentDAOImpl();

//创建动态代理类对象,并将被代理对象传递到代理类中赋值给obj
JDKDynamicProxy jdkDynamicProxy = new JDKDynamicProxy(studentDAO);

//proxy就是产生的代理对象:产生的代理对象可以强转成被代理对象实现的接口类型
GenaralDAO proxy = (GenaralDAO)jdkDynamicProxy.getProxy();

//使用代理对象调用方法,并不会执行调用的方法,
//而是进入到创建代理对象时指定的InvocationHandler类种的invoke方法
//调用的方法作为一个Method参数,传递给了invoke方法
proxy.insert(student);

4.2 CGLib动态代理实现

CGLib动态代理,是通过创建被代理类的子类来创建代理对象的,因此即使没有实现任何接口的类也可以通过CGLib产生代理对象

因为是创建子类,因此CGLib动态代理不能为final类创建代理对象

添加CGLib的依赖
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.3.0</version>
</dependency>
/**
 * 1.添加cglib依赖
 * 2.创建一个类,实现MethodInterceptor接口,同时实现接口中的intercept方法
 * 3.在类中定义一个Object类型的变量,并提供这个变量的有参构造器,用于传递被代理对象
 * 4.定义getProxy方法创建并返回代理对象(代理对象是通过创建被代理类的子类来创建的)
 */
public class CGLibDynamicProxy implements MethodInterceptor {

    private Object obj;
    public CGLibDynamicProxy(Object obj) {
        this.obj = obj;
    }

    public Object getProxy(){
        //字节码增强器对象,是cglib的核心对象,依靠他来生成代理类
        Enhancer enhancer = new Enhancer();
        // 告诉父类是谁(代理类是子类)
        enhancer.setSuperclass(obj.getClass());
        // 设置回调(等同于jdk动态代理中调用处理器 InvocationHandler)
        // 参数是 MethodInterceptor 方法拦截器对象
        enhancer.setCallback(this);
        // 创建代理对象。
        Object proxy = enhancer.create();
        return proxy;
    }


    // 调用和JDK动态代理是一样的,反射
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        begin();
        Object returnValue = method.invoke(obj,objects); //通过反射调用被代理类的方法
        commit();
        return returnValue;
    }

    public void begin(){
        System.out.println("----------开启事务");
    }

    public void commit(){
        System.out.println("----------提交事务");
    }
}


// ------------测试 ------------

//创建被代理对象
BookDAOImpl bookDAO = new BookDAOImpl();
StudentDAOImpl studentDAO = new StudentDAOImpl();

//通过cglib动态代理类创建代理对象
CGLibDynamicProxy cgLibDynamicProxy = new CGLibDynamicProxy(bookDAO);
//代理对象实际上是被代理对象子类,因此代理对象可直接强转为被代理类类型
BookDAOImpl proxy = (BookDAOImpl) cgLibDynamicProxy.getProxy();

//使用对象调用方法,实际上并没有执行这个方法,而是执行了代理类中的intercept方法,将当前调用的方法以及方法中的参数传递到intercept方法
proxy.update();

五、Spring AOP

5.1 AOP的概念

aspect oriented programming 面向切面编程,是一种利用横切的技术,对原有的业务逻辑进行拦截,并且可以在这个拦截的横切面上添加特点的业务逻辑,实现不改变代码对原有业务的增强。

底层的实现就是动态代理。

连接点 joinPoint:原始程序中的方法

切入点pointCut:被spring横切的方法

通知/增强:

切点:添加到切入点的 新增的业务方法

切面:定义切点方法的类

5.2 Spring AOP 框架部署

5.2.1 创建maven项目

5.2.2 添加依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.13.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.13.RELEASE</version>
</dependency>

5.3  AOP配置 --基于xml

例子:在DAO方法中添加开启事务和提交事务的逻辑

5.3.1 创建一个类,定义要添加的业务逻辑 --- 这个类就是切面,里面定义的方法就是切点

public class TxManager {
    public void begin(){
        System.out.println("-----------开启事务");
    }

    public void commit(){
        System.out.println("-----------提交事务");
    }
}

5.3.2 配置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
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="bookDAO" class="com.qfedu.dao.BookDAOImpl"></bean>
    <bean id="studentDAO" class="com.qfedu.dao.StudentDAOImpl"></bean>

    <!---->
    <bean id="txManager" class="com.qfedu.utils.TxManager"></bean>
    <aop:config>
        <!--声明切入点-->
        <aop:pointcut id="book_all" expression="execution(* com.qfedu.dao.*.*(..))"/>

        <!--声明txManager为切面类-->
        <aop:aspect ref="txManager">
            <!--通知-->
            <aop:before method="begin" pointcut-ref="book_all"/>
            <aop:after method="commit" pointcut-ref="book_all"/>
        </aop:aspect>
    </aop:config>

</beans>

总结AOP的开发步骤:

  1. 创建一个切面类,定义切点方法
  2. 将切面类配置给spring容器
  3. 声明切入点
  4. 配置AOP的通知策略

5.4 切入点的声明

5.4.1 各种切入点声明方式

<!--使用aop:pointcut标签声明切入点:切入点可以是一个方法-->
<aop:pointcut id="book_insert" expression="execution(* com.qfedu.dao.BookDAOImpl.insert())"/>

<!--BookDAOImpl类中所有无参数无返回值的方法-->
<aop:pointcut id="book_pc1" expression="execution(void com.qfedu.dao.BookDAOImpl.*())"/>

<!--BookDAOImpl类中所有无返回值的方法-->
<aop:pointcut id="book_pc2" expression="execution(void com.qfedu.dao.BookDAOImpl.*(..))"/>

<!--BookDAOImpl类中所有无参数的方法-->
<aop:pointcut id="book_pc3" expression="execution(* com.qfedu.dao.BookDAOImpl.*())"/>

<!--BookDAOImpl类中所有方法-->
<aop:pointcut id="book_pc4" expression="execution(* com.qfedu.dao.BookDAOImpl.*(..))"/>

<!--dao包中所有类中的所有方法-->
<aop:pointcut id="pc5" expression="execution(* com.qfedu.dao.*.*(..))"/>

<!--dao包中所有类中的insert方法-->
<aop:pointcut id="pc6" expression="execution(* com.qfedu.dao.*.insert(..))"/>

5.4.2 AOP使用的注意事项

如果要使用spring aop 面向切面编程,调用切入点方法的对象必须是通过spring容器获取的。

如果一个类中的方法被声明为切入点并织入了切点之后,通过spring容器获取该类对象,实际获取到的是一个代理对象

如果一个类中的方法没有被声明为切入点,通过spring容器获取的就是这个类真实的对象。

//BookServiceImpl bookService = new BookServiceImpl();
BookServiceImpl bookService = (BookServiceImpl) context.getBean("bookServiceImpl");
bookService.addBook();

5.5 AOP的通知策略

AOP的通知策略就是声明将切面类中的切点方法 如何织入到切入点

  • before -- 前置通知
  • after -- 后置 通知
  • after-throwing -- 异常之后的通知
  • after-returning -- 方法返回值之后,与 after的时机属于一个时间点,看那个先配置就先执行那个
  • around   -- 环绕通知,定义环绕通知的切点方法要遵守特定的规则
<bean id="myAspect" class="com.qfedu.utils.MyAspect"></bean>
<aop:config>
    <!--使用aop:pointcut标签声明切入点:切入点可以是一个方法-->
    <aop:pointcut id="book_insert" expression="execution(* com.qfedu.dao.BookDAOImpl.insert())"/>

    <aop:aspect ref="myAspect">
        <!--aop:before 前置通知,切入到指定切入点之前-->
        <aop:before method="method1" pointcut-ref="book_insert"/>
        <!--aop:after 后置通知,切入到指定切入点之后-->
        <aop:after method="method2" pointcut-ref="book_insert"/>
        <!--aop:after-throwing 异常通知,切入点抛出异常之后-->
        <aop:after-throwing method="method3" pointcut-ref="book_insert"/>
        <!--aop:after-returning 方法返回值返回之后,对于一个Java方法而言return返回值也是方法的一部分
             因此“方法返回值返回之后”和“方法执行结束”是同一个时间点,随意after 和 after-returning根据配置的顺序决定执行顺序-->
        <aop:after-returning method="method4" pointcut-ref="book_insert"/>
        
        <aop:around method="method5" pointcut-ref="book_insert"/>
    </aop:aspect>

</aop:config>
public class MyAspect {

    public void method1(){
        System.out.println("~~~~~~~method1");
    }
    public void method2(){
        System.out.println("~~~~~~~method2");
    }
    public void method3(){
        System.out.println("~~~~~~~method3");
    }
    public void method4(){
        System.out.println("~~~~~~~method4");
    }

    //环绕通知的切点方法,必须准守如下的定义规则:
    //1.必须带有一个ProceedingJoinPoint类型的参数
    //2.必须有Object类型的返回值
    //3.在前后增强的业务逻辑之间执行Object v = point.proceed();
    //4.方法最后返回v
    public Object method5(ProceedingJoinPoint point) throws Throwable {
        System.out.println("~~~~~~~method5---before");
        //此代码的执行,就表示切入点方法的执行
        Object v = point.proceed();
        System.out.println("~~~~~~~method5---after");
        return v;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值