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 的 ...
随机推荐
- LeetCode 1140. Stone Game II
原题链接在这里:https://leetcode.com/problems/stone-game-ii/ 题目: Alex and Lee continue their games with pile ...
- LeetCode 930. Binary Subarrays With Sum
原题链接在这里:https://leetcode.com/problems/binary-subarrays-with-sum/ 题目: In an array A of 0s and 1s, how ...
- 洛谷 P1717 钓鱼 题解
每日一题 day46 打卡 Analysis 首先通过题目我们不难发现,为了得到最优解,那么就不能把时间浪费在路上,也就是说不能走回头路.然后很容易可以发现,在每个时刻在不同的鱼塘钓到的鱼的数量是不同 ...
- 关于异常System.ArgumentException
什么是System.ArgumentException 当向方法提供的参数之一无效时引发的异常. 继承 Object Exception SystemException ArgumentExcepti ...
- Python 02 编写代码
原文:https://www.cnblogs.com/jimmy-share/p/9784219.html 方式: 交互式编程:打开python.exe文件后,直接输入代码即可.文件的位置(我本地): ...
- 79: cf 444E 并查集+思维
$des$ 题面 $sol$ 把边从小到大排序,枚举每条边作为答案,然后把两个点合并,判断每条边是否可以作为答案时,$cnt_i$ 表示节点 $i$ 已经合并的 $x$ 之和$size_i$ 表示已经 ...
- TypeScript规则整理
介绍我在初学 TS 开发项目中遇到的一些问题,希望对你有所帮助~ 因为我们的JavaScript是弱类型语言,如果项目过大,或者团队人数很多,不仅代码风格不统一,以后还会很难维护 Ty ...
- LeetCode 7. 反转整数(Reverse Integer)
题目描述 给定一个 32 位有符号整数,将整数中的数字进行反转. 示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 ...
- dockerfile文件语法命令
dockerfile文件语法命令 (1) FROM命令,支持两种形式,构建新镜像使用的基础镜像,所以源镜像必须存在,并且是非注释的第一条命令. DOCKERFILEFORM <image> ...
- max函数比较字符串类型
关于sql中 max函数比较字符串类型 max只比较首个字符的大小 只要首字母大,则不比较其他位置的字母,若首字母相同,则比较顺序位字母. 今天死在这了 数据库中 step字段类型char分别为 5. ...