Spring笔记3
动态代理**
特点:字节码随用随创建,随用随加载
作用:不修改源码的基础上对方法增强
分类:
基于接口的动态代理
基于子类的动态代理
基于接口的动态代理:
涉及的类: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的更多相关文章
- Spring笔记02_注解_IOC
目录 Spring笔记02 1. Spring整合连接池 1.1 Spring整合C3P0 1.2 Spring整合DBCP 1.3 最终版 2. 基于注解的IOC配置 2.1 导包 2.2 配置文件 ...
- Spring笔记01_下载_概述_监听器
目录 Spring笔记01 1.Spring介绍 1.1 Spring概述 1.2 Spring好处 1.3 Spring结构体系 1.4 在项目中的架构 1.5 程序的耦合和解耦 2. Spring ...
- Spring 笔记 -06- 从 MySQL 建库到 登录验证数据库信息(maven)
Spring 笔记 -06- 从 MySQL 建库到 登录验证数据库信息(maven) 本篇和 Spring 没有什么关系,只是学习 Spring,必备一些知识,所以放在这里了. 本篇内容: (1)M ...
- Spring笔记:事务管理
Spring笔记:事务管理 事务管理 Spring事务管理是通过SpringAOP去实现的.默认情况下Spring在执行方法抛出异常后,引发事务回顾,当然你可以用拦截器或者配置去改变它们. 这部门内容 ...
- Spring笔记:AOP基础
Spring笔记:AOP基础 AOP 引入AOP 面向对象的开发过程中,我们对软件开发进行抽象.分割成各个模块或对象.例如,我们对API抽象成三个模块,Controller.Service.Comma ...
- Spring:笔记整理(1)——HelloWorld
Spring:笔记整理(1)——HelloWorld 导入JAR包: 核心Jar包 Jar包解释 Spring-core 这个jar 文件包含Spring 框架基本的核心工具类.Spring 其它组件 ...
- Spring笔记:IOC基础
Spring笔记:IOC基础 引入IOC 在Java基础中,我们往往使用常见关键字来完成服务对象的创建.举个例子我们有很多U盘,有金士顿的(KingstonUSBDisk)的.闪迪的(SanUSBDi ...
- Spring笔记(6) - Spring的BeanFactoryPostProcessor探究
一.背景 在说BeanFactoryPostProcessor之前,先来说下BeanPostProcessor,在前文Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析中讲解了Be ...
- spring笔记----看书笔记
上周末看了一章以前javaee轻量级的书spring部分,简单做了一些笔记 // ApplicationContext ac=new ClassPathXmlApplicationContext(&q ...
- Spring 笔记(三)Bean 装配
前言 Spring 有两大核心,也就分成两份笔记分别记录. 其一是管理应用中对象之间的协作关系,实现方式是依赖注入(DI),注入依赖的过程也被称为装配(Wiring). 基于 JavaConfig 的 ...
随机推荐
- go正则表达式
单行模式(?s:(.?))万能用法尽量匹配少的文本,最关键的是可以匹配换行的文本,直接写.?不能匹配\n package main import ( "fmt" "reg ...
- 洛谷 UVA12101 Prime Path 题解
一道经典的BFS 用四个for搜索四位就行了,只要能推出怎么只变4位中的一位就很水了 #include<iostream> #include<cstring> #include ...
- RSDS pdb格式
本描述了“RSDS”或“DS”类型的pdb(程序数据库)文件的格式,这些文件是由Miscrosoft的link.exe从版本7及更高版本发出的. 什么是PDB文件? 如果选择了/DEBUG选项或/DE ...
- vuex 之既生‘mutation’何生‘action’
vuex 中,action 及 mutation 均为操作数据的作用而存在,既然二者均可改变数据,为什么要分成两个方法来处理呢,因为: Mutation 必须是同步函数 mutations: { so ...
- 1.typescirpt学习之路,*.d.ts和@types关系理解
今天看了看ts,文档上很多没用讲,小编疑惑了很久一个问题! *.d.ts和@types啥关系,小编查阅了很多文档,才弄明白. 首先,@types是npm的一个分支,我们把npm包发上去,npm包就会托 ...
- gulp+webpack多页应用开发,webpack仅处理打包js
项目背景:一个综合网站,开发模式为后端嵌套数据,前端开发静态页面和部分组件. 问题:gulp任务处理自动刷新.sass编译等都是极好的.但是对于js的处理并不是很好,尤其是项目需要开发组件时候,如评论 ...
- SSL 安全协议 以及 如何认证
目录 ssl安全协议 以及 认证 什么是协议 http劫持 ssl是什么 ssl 证书 概念 3种类型ssl 证书 ssl认证:阿里云免费认证 配置 Nginx的ssl认证 nginx的ssl证书(一 ...
- MySQL免安装配置步骤
此方式为直接解压压缩包安装MySQL 1.下载相关压缩包 官网下载地址:https://dev.mysql.com/downloads/mysql/ 下载后将压缩包解压至自己想要的文件路径即可 2.新 ...
- MYSQL事务的开启与提交
MYSQL 事务处理主要有两种方法: 1.用 BEGIN, ROLLBACK, COMMIT来实现 BEGIN 开始一个事务 ROLLBACK 事务回滚 COMMIT 事务确认 2.直接用 SET 来 ...
- 如何在真实串口驱动还未加载的情况下调试uboot?
1. 先找出真实串口是什么型号 1.1 怎么找?笔者提供两种方案: 方案一: 若当前的板子支持dm,从uboot的dts找串口节点对应的compatible属性 方案二: 从linux内核的dts找串 ...