动态代理**

特点:字节码随用随创建,随用随加载

作用:不修改源码的基础上对方法增强

分类:

​ 基于接口的动态代理

​ 基于子类的动态代理

基于接口的动态代理:

涉及的类:Proxy

如何创建代理对象:

​ 使用Proxy类中的newProxyInstance方法

创建代理对象的要求:被代理的类最少实现一个接口,如果没有则不能使用

newProxyInstance方法的参数:

ClassLoader :类加载器,他是用于加载代理对象字节码的,和被代理使用相同的类加载器

Class[] :字节码数组:他是用于让代理对象和被代理对象有相同方法

InvocationHandler:用于提供增强的代码,他是让我们写如何代理,一般都是些一个该接口的实现类,通常情况下都是匿名内部类

package com.itheima;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
producer.saleProduct(10000f); Iproducer proxyProducer = (Iproducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
//该方法的作用,具有拦截功能
//执行被代理对象的任何接口方法都会经过该方法
//proxy:代理对象的引用
//Method:当前执行的方法
//args:当前执行方法所需的参数
//return:和被代理对象方法有相同的返回值
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//提供增强的代码
Object returnValue = null;
//获取方法执行的参数
Float money = (Float)args[0];
//判断当前方法
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
}
}

基于子类的动态代理

需要导入cglib包

涉及的类:Enhancer

如何创建代理对象:使用Enhancer类中的create方法

创建代理对象的要求:被代理类不能是最终类

create方法的参数

Class:字节码,用于指定被代理对象的字节码

Callback:用于提供增强的代码,一般写的都是该接口的子接口实现类,MethodInterceptor

package com.itheima.cglib;

import com.itheima.Iproducer;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
producer.saleProduct(10000f); Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() { public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//提供增强的代码
Object returnValue = null;
//获取方法执行的参数
Float money = (Float)objects[0];
//判断当前方法
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
cglibProducer.saleProduct(10000f);
}
}

AOP:全称是Aspect Oriented Programming 面向切面编程

把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强

AOP相关术语

Joinpoint(连接点):所谓连接点是值那些被拦截到的点,在spring中,这些点指的是方法,因为spring只支持方法类型的连接点

pointcut(切入点):所谓切入点是指我们要对哪些JoinPoint进行拦截的定义(被增强的方法才是切入点)

Advice(通知/增强):所谓的通过指的是拦截到Joinpoint之后所要做的事情就是通知,通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知

Target(目标对象):代理的目标对象

Weaving(织入):指的是把增强应用到目标对象来创建新的代理对象的过程

Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类

Aspect(切面):是切入和通知的结合

spring基于XML的AOP

1.导入两个坐标

<?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>com.itheima</groupId>
<artifactId>day03_eesy_03springAOP</artifactId>
<version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.3.RELEASE</version>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
</project>

2.创建业务层和dao层

package com.itheima.service.impl;

import com.itheima.service.IAccountService;

//账户业务层实现类
public class AccountServiceImpl implements IAccountService { public void saveAccount() {
System.out.println("执行了保存");
} public void updateAccount(int i) {
System.out.println("执行了更新");
} public int deleteAccount() {
System.out.println("执行了删除");
return 0;
}
}

3.准备一个具有公共代码的类

package com.itheima.utils;
//用于记录日志的工具类,他里面提供了公共的代码
public class Logger {
//用于打印日志:计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)
public void printLog(){
System.out.println("Logger类中的方法开始记录日志了");
}
}

目的:在执行业务层的方法之前,先执行printLog方法,通过spring配置的方式来完成,不使用动态代理

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: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">
<!--配置spring的Ioc,把service对象配置进来-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean> <!--spring中基于xml的AOP配置步骤
1.把通知Bean也交给spring来管理
2.使用aop:config标签表名开始AOP的配置
3.使用aop:aspect标签表明配置切面
id属性:是给切面提供一个唯一标识
ref属性:是指定通知类bean的Id
4.在aop:aspect标签的内部使用对象标签来配置通知的类型
我们现在的示例是让printLog方法在切入点方法执行之前执行,所以是前置通知
method属性:用于指定Logger类中哪个方法是前置通知
pointcut属性:用于指定切入点表达式,该表达式含义指的是对业务层中哪些方法增强
切入点表达式的写法:
关键字:execution(表达式)
表达式:访问修饰符 返回值 包名.包名.包名....类名.方法(参数列表)
-->
<!--配置Logger类-->
<bean id="logger" class="com.itheima.utils.Logger"></bean> <!--配置AOP-->
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知类型,并且建立通知方法和切入点方法的关联-->
<aop:before method="printLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:before>
</aop:aspect> </aop:config>
</beans>

5.测试类

package com.ithei.test;

import com.itheima.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; //测试AOP的配置
public class AOPTest {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取UI小
IAccountService as = (IAccountService)ac.getBean("accountService");
//3.执行方法
as.saveAccount();
}
}

控制台输出:

Logger类中的方法开始记录日志了
执行了保存

切入点表达式: execution(* com.itheima.service.impl..(..))

四种通知的配置

<!--配置AOP-->
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知类型,并且建立通知方法和切入点方法的关联-->
<!--前置通知-->
<aop:before method="beforePrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before>
<!--后置通知-->
<aop:after-returning method="afterReturningPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after-returning>
<!--异常通知-->
<aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after-throwing>
<!--最终通知-->
<aop:after method="afterPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after>
</aop:aspect>
</aop:config>

Spring笔记3的更多相关文章

  1. Spring笔记02_注解_IOC

    目录 Spring笔记02 1. Spring整合连接池 1.1 Spring整合C3P0 1.2 Spring整合DBCP 1.3 最终版 2. 基于注解的IOC配置 2.1 导包 2.2 配置文件 ...

  2. Spring笔记01_下载_概述_监听器

    目录 Spring笔记01 1.Spring介绍 1.1 Spring概述 1.2 Spring好处 1.3 Spring结构体系 1.4 在项目中的架构 1.5 程序的耦合和解耦 2. Spring ...

  3. Spring 笔记 -06- 从 MySQL 建库到 登录验证数据库信息(maven)

    Spring 笔记 -06- 从 MySQL 建库到 登录验证数据库信息(maven) 本篇和 Spring 没有什么关系,只是学习 Spring,必备一些知识,所以放在这里了. 本篇内容: (1)M ...

  4. Spring笔记:事务管理

    Spring笔记:事务管理 事务管理 Spring事务管理是通过SpringAOP去实现的.默认情况下Spring在执行方法抛出异常后,引发事务回顾,当然你可以用拦截器或者配置去改变它们. 这部门内容 ...

  5. Spring笔记:AOP基础

    Spring笔记:AOP基础 AOP 引入AOP 面向对象的开发过程中,我们对软件开发进行抽象.分割成各个模块或对象.例如,我们对API抽象成三个模块,Controller.Service.Comma ...

  6. Spring:笔记整理(1)——HelloWorld

    Spring:笔记整理(1)——HelloWorld 导入JAR包: 核心Jar包 Jar包解释 Spring-core 这个jar 文件包含Spring 框架基本的核心工具类.Spring 其它组件 ...

  7. Spring笔记:IOC基础

    Spring笔记:IOC基础 引入IOC 在Java基础中,我们往往使用常见关键字来完成服务对象的创建.举个例子我们有很多U盘,有金士顿的(KingstonUSBDisk)的.闪迪的(SanUSBDi ...

  8. Spring笔记(6) - Spring的BeanFactoryPostProcessor探究

    一.背景 在说BeanFactoryPostProcessor之前,先来说下BeanPostProcessor,在前文Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析中讲解了Be ...

  9. spring笔记----看书笔记

    上周末看了一章以前javaee轻量级的书spring部分,简单做了一些笔记 // ApplicationContext ac=new ClassPathXmlApplicationContext(&q ...

  10. Spring 笔记(三)Bean 装配

    前言 Spring 有两大核心,也就分成两份笔记分别记录. 其一是管理应用中对象之间的协作关系,实现方式是依赖注入(DI),注入依赖的过程也被称为装配(Wiring). 基于 JavaConfig 的 ...

随机推荐

  1. LeetCode 837. New 21 Game

    原题链接在这里:https://leetcode.com/problems/new-21-game/ 题目: Alice plays the following game, loosely based ...

  2. LeetCode 1130. Minimum Cost Tree From Leaf Values

    原题链接在这里:https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ 题目: Given an array arr of ...

  3. WinDbg常用命令系列---异常相关操作

    .exr (Display Exception Record) .exr命令显示异常记录的内容. .exr Address .exr -1 参数: Address指定异常记录的地址.如果指定-1作为地 ...

  4. Nodejs中的路径问题

    一.path核心模块 ①path.basename(path[,ext])获取一个路径中的文件名 var path=require('path'); console.log(path.basename ...

  5. node.js切换多个版本

    开言 试用场景就是我们开发项目的时候,有可能一个项目需要v10版本,另一个项目需要v8版本,遇到这种问题,我们不能卸载再重新安装对应的版本去开发,遇到这样的问题的时候,那我们就可以去用另一种方式去切换 ...

  6. plsql 如何导入excel数据?

      oracle 导入excel数据? 通过plsql实现 1.准备工作 Excel中的字段名称,必须和表结构字段一 一对应 下面以tdoctor_apply表为例,进行演示 表结构 Excel表数据 ...

  7. [C++] 对象指针使用方法

    对象指针:指向类对象的指针 类指针指向类变量(对象)的地址 对象指针定义格式: 类类型 *变量名: 举例: #include <iostream> using namespace std; ...

  8. 在mybatis中写sql语句的一些体会

    本文会使用一个案例,就mybatis的一些基础语法进行讲解.案例中使用到的数据库表和对象如下: article表:这个表存放的是文章的基础信息 -- ------------------------- ...

  9. MacBook Air装Windows7双系统后的一些(未尝试)想法

    转载请标注原地址:https://www.cnblogs.com/lixiaojing/p/11458477.html 运行环境: macOS在Mojave下的Boot Camp Assistant只 ...

  10. #C++初学记录ACM补题(D. Candies!)前缀和运算。

    D - Candies!   Consider a sequence of digits of length [a1,a2,-,a]. We perform the following operati ...