动态代理**

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

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

分类:

​ 基于接口的动态代理

​ 基于子类的动态代理

基于接口的动态代理:

涉及的类: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. 笨办法学Python

    打印:%r%r 与 %s 的区别就好比 repr() 函数处理对象与 str() 函数处理对象的差别.%s => str(),比较智能%r => repr(),处理较为简单和直接 from ...

  2. Call to undefined function imagecreatefromjpeg() 让GD支持JPEG格式的图片扩展

    安装扩展支持jpeg格式: 第一步:首先下载文件: 版本v8: wget http://www.ijg.org/files/jpegsrc.v8b.tar.gz 版本v9: wget http://w ...

  3. nginx之别名、location使用

    alias server { listen 80; server_name www.xxxpc.net ~^www\.site\d+\.net$; error_page 500 502 503 504 ...

  4. GoCN每日新闻(2019-10-21)

    GoCN每日新闻(2019-10-21) GoCN每日新闻(2019-10-21)   1. 使用 Golang, RabbitMQ 和 Protobuf 构建高效的微服务 https://mediu ...

  5. mysql max()函数,min()函数,获取最大值以及最小值

    mysql> select * from table1; +----------+------------+-----+---------------------+ | name_new | t ...

  6. ASP.NET MVC5+EF6+EasyUI 后台管理系统-代码生成器用法

    新的代码生成器比老的更加容易使用,要生成什么形式就选择什么形式,新的代码生成器采用的是WCF界面开发,同样采用开源的模式,根据自己使用习惯容易扩展 1.单列表模式 2.树形列表模式 3.左右列表模式 ...

  7. ubuntu之路——day16 只用python的numpy在底层检验神经网络的优化算法

    首先感谢这位博主整理的Andrew Ng的deeplearning.ai的相关作业:https://blog.csdn.net/u013733326/article/details/79827273 ...

  8. 【大数据】安装关系型数据库MySQL安装大数据处理框架Hadoop

    作业来源于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/3161 1. 简述Hadoop平台的起源.发展历史与应用现状. 列举发展过 ...

  9. Jmeter工具功能介绍

    可以去官方学习:http://jmeter.apache.org/ 1.可以修改语言 2.部分图标功能 新建 打开一个jmeter脚本 保存一个jmeter脚本 剪切 复制 粘贴 展开目录树 收起目录 ...

  10. Research Guide for Neural Architecture Search

    Research Guide for Neural Architecture Search 2019-09-19 09:29:04 This blog is from: https://heartbe ...