Spring学习笔记

目录

一、IOC开发

1.IOC介绍(百度百科)

6.纯注解开发

二、AOP 开发

1.AOP介绍(百度百科)

2.AOP底层原理

3.AOP(JDK 动态代理)

4.AOP (术语)

5.AOP 操作(准备工作)

6.AOP 操作(AspectJ注解)

7.AOP 操作(AspectJ配置文件)


一、IOC开发

1.IOC介绍(百度百科)

控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。

6.纯注解开发

(1) 创建配置类,替代xml配置文件

创建config包,包里放入SpringConfig类

package com.aotao.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.aotao"})
public class SpringConfig {
}

(2) 编写测试类

package com.aotao.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.aotao"})
public class SpringConfig {

}

(3)加载测试类

public static void testService2(){
        //1.加载spring配置文件
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        //2.获取配置创建的对象
        UserService1 userService1 = context.getBean("userService1", UserService1.class);

        System.out.println(userService1);
        userService1.add();
    }

二、AOP 开发

1.AOP介绍(百度百科)

(1) 什么是AOP

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

简答来说就是不通过修改源代码方式添加新的功能,即在主干功能中添加indeed功能

 

2.AOP底层原理

(1) AOP底层使用动态代理

第一种 有接口情况,使用JDK动态代理

  • 创建UserDao接口实现类代理对象

第二种 没有接口情况,使用CGLIB动态代理

  • 创建当前子类的代理对象

 

3.AOP(JDK 动态代理)

(1) 使用JDK动态代理,使用Proxy类里面的方法创建代理对象

调用newProxyInstance方法

方法有三个参数:

第一个参数,类加载器

第二个参数,增强方法所在的类,这个类实现的接口,支持多个接口

第三个参数,实现这个接口InvocationHandler,创建代理对象,写增强方法

(2) 编写JDK动态代理代码

1 创建接口UserDao,定义方法

public interface UserDao {
    public int add(int a,int b);
    
    public String update(String id);
}

2 创建接口实现类UserDaoImpl,实现方法

public class UserDaoImpl implements UserDao{
    public int add(int a, int b) {
        return a+b;
    }

    public String update(String id) {
        return id;
    }
}

3 使用Proxy类创建接口代理对象JDKProxy,底层原理

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

public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};
//        Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//
//
//            }
//        });
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = dao.add(1, 2);
        System.out.println("Result:"+add);
    }
}

class UserDaoProxy implements InvocationHandler {

    //1 把创建的是谁的代理对象,把谁传递过来,这里的谁就是UserDaoImpl
    //有参数构造传递
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj = obj;
    }

    //增强逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //方法之前
        System.out.println("方法之前执行……["+method.getName()+"] :传递的参数……"+ Arrays.toString(args));

        //被增强的方法执行
        Object res = method.invoke(obj, args);

        //方法之后
        System.out.println("方法之后执行……"+obj);

        return res;
    }
}

 

4.AOP (术语)

1 连接点

类里面哪些方法可以被增强,这些方法称为连接点。

2 切入点

实际被真正增强的方法,成为切入点

3 通知 (增强)

(1)实际被增强的逻辑部分被称为通知(增强)

(2)通知有多种类型

  • 前置通知(方法执行之前执行)
  • 后置通知(方法执行之后执行)
  • 环绕通知(方法执行之前和之后都会执行)
  • 异常通知(方法出现异常会出现)
  • 最终通知(类似finally)

4 切面

切面是一个动作

  • 把通知应用到切入点过程

 

5.AOP 操作(准备工作)

(1) Spring框架一般基于AspectJ实现AOP操作

1 什么是AspectJ

  • AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作

 (2) 基于AspectJ实现AOP操作

  • 基于xml配置文件
  • 基于注解方式实现

(3) 在项目工程里面引入AOP相关依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>


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


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

(4) 切入点表达式

  • 切入点表达式的作用:知道对哪个类里面的哪个方法进行增强
  • 语法结构:execution( [权限修饰符] [返回类型] [类全路径] [方法名称] ([参数列表]) )

举例1:对com.aotao.dao.BookDao类里面的add方法进行增强

execution(*com.aotao.dao.BookDao.add(..))

举例2:对com.aotao.dao.BookDao类里面的所有方法进行增强

execution(*com.aotao.dao.BookDao.*(..))

举例2:对com.aotao.dao包里面的所有类所有方法进行增强

execution(*com.aotao.dao.*.*(..))

 

6.AOP 操作(AspectJ注解)

(1) 创建类,在类里面定义方法

//被增强的类
public class User {
    public void add(){
        System.out.println("add.........");
    }
}

(2) 创建增强类(编写增强逻辑)

在增强类里面创建方法,让不同方法代表不同通知类型

//增强的类
public class UserProxy {
    //前置通知
    public void before() {
        System.out.println("before>>>>>>");
    }
}

(3) 进行通知的配置

a.在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:component-scan base-package="com.aotao.AOP.ano"></context:component-scan>
</beans>

b.使用注解创建User和UserProxy对象

 

c.在增强类上面添加注解@Aspect

d.在spring的配置文件中开启生成代理对象

<!--开启AspectJ生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

(4) 配置不同类型的通知

 a.在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

//增强的类
@Component
@Aspect
public class UserProxy {
    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "execution(* com.aotao.AOP.ano.User.add(..))")
    public void before() {
        System.out.println("before>>>>>>");
    }

    //最终通知
    @After(value = "execution(* com.aotao.AOP.ano.User.add(..))")
    public void after(){
        System.out.println("after>>>>>>>>>");
    }

    //异常通知 当方法有异常执行
    @AfterThrowing(value = "execution(* com.aotao.AOP.ano.User.add(..))")
    public void afterThrowing(){
        System.out.println("afterThrowing>>>>>>>>>");
    }

    //返回通知
    @AfterReturning(value = "execution(* com.aotao.AOP.ano.User.add(..))")
    public void afterReturning(){
        System.out.println("afterReturning>>>>>>>>>");
    }


    //环绕通知
    @Around(value = "execution(* com.aotao.AOP.ano.User.add(..))")
    public void Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("环绕之前>>>>>>>>>");

        //被增强的方法执行
        proceedingJoinPoint.proceed();

        System.out.println("环绕之后>>>>>>>>>");
    }
}

b.编写测试类TestAop

public class TestAop {
    public static void testAopAnno(){
        ApplicationContext context = new ClassPathXmlApplicationContext("ano.xml");
        User user = context.getBean("user", User.class);
        user.add();
    }

    public static void main(String[] args) {
        testAopAnno();
    }
}

(5) 相同的切入点抽取

    //相同切入点抽取
    @Pointcut(value = "execution(* com.aotao.AOP.ano.User.add(..))")
    public void pointDemo(){
        
    }
    
    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "pointDemo()")
    public void before() {
        System.out.println("before>>>>>>");
    }

(6) 有多个增强类对同一个方法进行增强,可以设置增强类的优先级

a.在增强类上面添加注解@Order(数字类型值) 数值越小优先级越高

@Component
@Aspect
@Order(1)
public class UserProxy
@Component
@Aspect
@Order(3)
public class PersonProxy

 

(7) 使用完全注解开发

创建配置类,不需要创建xml配置文件

@Configuration
@ComponentScan(basePackages = {"com.aotao.Aop"}) //开启组件扫描
@EnableAspectJAutoProxy(proxyTargetClass = true) //开启AspectJ生成代理对象
public class ConfigAop {}

 

7.AOP 操作(AspectJ配置文件)

(1) 创建两个类,增强类和被增强类,创建方法

public class Book {
    public void buy() {
        System.out.println("buy>>>>>>>>>");
    }
}
public class BookProxy {
    public void before() {
        System.out.println("before>>>>>>>>>");
    }
}

(2) 在spring配置文件中创建两个类对象

<!--创建对象-->
<bean id="book" class="com.aotao.AOP.xml.Book"></bean>
<bean id="bookProxy" class="com.aotao.AOP.xml.BookProxy"></bean>

(3) 在spring配置文件中配置切入点

    <!--配置aop增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.aotao.AOP.xml.Book.buy(..))"/>
        
        <!--配置切面-->
        <aop:aspect ref="bookProxy">
            <!--配置增强作用在具体方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>

(4) 完整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"
       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">

    <!--创建对象-->
    <bean id="book" class="com.aotao.AOP.xml.Book"></bean>
    <bean id="bookProxy" class="com.aotao.AOP.xml.BookProxy"></bean>

    <!--配置aop增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.aotao.AOP.xml.Book.buy(..))"/>

        <!--配置切面-->
        <aop:aspect ref="bookProxy">
            <!--配置增强作用在具体方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
</beans>

AOP就完成了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值