AOP是什么?Spring中的AOP如何实现
lipiwang 2024-11-13 13:38 28 浏览 0 评论
满怀忧思,不如先干再说!持续高频更新技术文章,值得持续关注哦!
一、AOP介绍
1.1、概述
AOP的全称是Aspect Oriented Programming翻译过来就是面向切面编程,它的宗旨是在不修改源代码的前提下扩展功能,比如我们想要在代码原有的功能上去扩展功能在没有AOP的情况下就需要修改源代码,很不方便程序的扩展、维护,这将是一场灾难,有了AOP之后我们不用修改源代码通过切面就可以扩展功能,怎么理解切面呢?
比如我们想要吃肉夹馍,在没有AOP的时候我们需要再做一个烙一个带肉的现成的肉夹馍,有了AOP之后呢,不需要重新烙一个馍,而是在馍的中间来一刀,这个就是切面,在中间加上肉就可以了。其实AOP是对OOP的补充,让我们开发程序变得更优雅
1.2、应用场景
1、性能检测
2、访问控制
3、事务管理
4、缓存
5、日志模块等
1.3、AOP优点
1、集中处理项目的业务问题抽取出来单独编写
2、减少代码冗余
3、提高程序的维护性和扩展性等
1.4、专业术语
1、通知(Advice)
就是扩展的功能,比如我们的程序中需要添加日志,事务等功能,编写该功能的方法就是通知,也可以称为增强。
通知分为前置通知,后置通知,环绕通知,异常通知等,说明加在什么位置,什么时候调用。
2、连接点(JoinPoint)
可以增强的功能,比如添加、删除、修改、查询等方法。
3、切入点(Pointcut)
实际上增强的方法,就比如我们增强添加的功能,这个添加的方法就是切入点。
4、切面(Aspect)
切入点、增强所在的那个类叫切面,这些代码需要编写出来,这个配置的类就是这个切面。
5、引入(introduction)
允许我们向现有的类添加新方法属性。这不就是把切面(也就是新方法属性:通知定义的)用到目标类中吗。
6、目标(target)
引入中所提到的目标类,也就是要被通知的对象,也就是真正的业务逻辑,他可以在毫不知情的情况下,被咱们织入切面。而自己专注于业务本身的逻辑。
7、代理(proxy)
AOP都是通过代理模式实现
8、织入(weaving)
把切面应用到目标对象来创建新的代理对象的过程。一共有3种方式,spring采用的是运行时织入
二、实现
2.1、实现方式
在Spring中使用aspectj实现AOP操作,注意aspectj并不是Spring中的一部分,只是和Spring一起使用,Spring2.x之后支持对aspectj的支持。使用aspectj对AOP的操作实现有xml配置和注解两种方式
2.2、pom依赖
添加aop和aspectj依赖
<!--aop依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.19</version>
</dependency>
<!-- aspectj支持 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
2.3、xml文件实现方式
2.3.1、业务类
package com.stt.service;
/**
操作用户的Dao层
*/
public class UserService {
//添加用户功能
public void addUser(){
System.out.println("添加用户");
}
//添加用户功能
public void deleteUser(){
System.out.println("删除用户");
}
//添加用户功能
public void updateUser(){
System.out.println("修改用户");
}
//添加用户功能
public void queryUser(){
System.out.println("查询用户");
}
}
2.3.2、增强类
package com.stt.advice;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 用户的日志类,在对用户进行修改操作时添加上时间
*/
public class UserLog {
/**
* 前置通知:即在做增删改操作前调用该方法
* 作用:生成时间
*/
public void getTime(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
System.out.println("当前时间为"+time);
}
/**
* 后置通知:即在做增删改操作后调用该方法
* 作用:提示操作成功
*/
public void success(){
System.out.println("操作成功");
}
}
2.3.3、applicationContext.xml
本来对用户的操作只打印对应的信息,现在操作增删前会打印时间,操作会输出成功
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="userService" class="com.stt.service.UserService"></bean>
<!--创建增强类对象-->
<bean id="userlog" class="com.stt.advice.UserLog"></bean>
<!--配置aop-->
<aop:config>
<!--配置切入点,就是哪些方法要进行增强,这里需要写表达式
execution(<访问修饰符>?<返回值类型><方法名>(<参数>)<异常>)
1. execution (* com.stt.service.UserService.add*(..)) UserService类中以add开头的方法
2. execution (* com.stt.service.UserService.*(..))UserService类中的所有方法
3. execution (* *.*(..))所有方法
4. execution (* save*(..))匹配所有save开头的方法
......
多个表达式间使用 or 隔开
-->
<aop:pointcut id="pointcut1" expression="execution(* com.stt.service.UserService.addUser(..)) or
execution(* com.stt.service.UserService.updateUser(..)) or
execution(* com.stt.service.UserService.deleteUser(..))"></aop:pointcut>
<!--配置切面
将增强使用在切入点的过程
-->
<aop:aspect ref="userlog">
<!--前置通知使用aop before标签
method:填写增强类中的方法
pointcut-ref:填写上班切入点的id
-->
<aop:before method="getTime" pointcut-ref="pointcut1"></aop:before>
<!--后置通知使用after-->
<aop:after method="success" pointcut-ref="pointcut1"></aop:after>
</aop:aspect>
</aop:config>
</beans>
2.3.4、测试
调用的是addUser方法但是该方法前后后有对应数据输出就是我们使用aop配置的,并没有修改UserService的源代码只是定义增强类和增强方法,使用xml配置文件将功能添加上去,极大提升扩展性和维护性。
2.4、注解实现
2.4.1、业务类
package com.stt.service;
import org.springframework.stereotype.Service;
/**
操作用户的Service层
*/
@Service("userService")
public class UserService {
//添加用户功能
public void addUser(){
System.out.println("添加用户");
}
//添加用户功能
public void deleteUser(){
System.out.println("删除用户");
}
//添加用户功能
public void updateUser(){
System.out.println("修改用户");
}
//添加用户功能
public void queryUser(){
System.out.println("查询用户");
}
}
2.4.2、增强类
package com.stt.advice;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 用户的日志类,在对用户进行修改操作时添加上时间
* 添加@Aspect注解
*/
@Aspect
@Component("userLog")
public class UserLog {
/**
* 前置通知:即在做增删改操作前调用该方法
* 作用:生成时间
*/
@Before(value = "execution(* com.stt.service.UserService.addUser(..)) || " +
" execution(* com.stt.service.UserService.updateUser(..)) || " +
" execution(* com.stt.service.UserService.deleteUser(..))")
public void getTime(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
System.out.println("当前时间为"+time);
}
/**
* 后置通知:即在做增删改操作后调用该方法
* 作用:提示操作成功
*/
@After(value = "execution(* com.stt.service.UserService.addUser(..)) || " +
" execution(* com.stt.service.UserService.updateUser(..)) || " +
" execution(* com.stt.service.UserService.deleteUser(..))")
public void success(){
System.out.println("操作成功");
}
}
2.4.3、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.stt"/>
<!--开启aop操作-->
<aop:aspectj-autoproxy/>
</beans>
2.4.4、测试
三、AOP原理
3.1、概述
? Spring中AOP的实现方式其实是代理模式,代理模式是给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。通俗的来讲代理模式就是我们生活中常见的中介。代理模式分为静态代理和动态代理。静态代理是由程序员创建或特定工具自动生成源代码,再对其编译。在程序运行之前,代理类.class文件就已经被创建了。动态代理是在程序运行时通过反射机制动态创建的。
3.2、为什么使用代理模式
?中介隔离作用:在某些情况下,一个客户类不想或者不能直接引用一个委托对象,而代理类对象可以在客户类和委托对象之间起到中介的作用,其特征是代理类和委托类实现相同的接口。
?开闭原则,增加功能:代理类除了是客户类和委托类的中介之外,我们还可以通过给代理类增加额外的功能来扩展委托类的功能,这样做我们只需要修改代理类而不需要再修改委托类,符合代码设计的开闭原则。代理类主要负责为委托类预处理消息、过滤消息、把消息转发给委托类,以及事后对返回结果的处理等。代理类本身并不真正实现服务,而是同过调用委托类的相关方法,来提供特定的服务。真正的业务功能还是由委托类来实现,但是可以在业务功能执行的前后加入一些公共的服务。例如我们想给项目加入缓存、日志这些功能,我们就可以使用代理类来完成,而没必要打开已经封装好的委托类。
3.3、静态代理
3.3.1、接口
package com.stt.service;
/**
* 定义接口
*/
public interface IPersonService {
void speak();
}
3.3.2、实现类
package com.stt.service.impl;
import com.stt.service.IPersonService;
/**
实现类
*/
public class PersonService implements IPersonService {
public void speak() {
System.out.println("君不见,高堂明镜悲白发,朝如青丝暮成雪。");
}
}
3.3.3、代理对象
package com.stt.service.impl;
import com.stt.service.IPersonService;
/**
* ClassName: PersonServiceProxy
* Description:
* date: 2019/10/17 0017 下午 20:31
*
* @author stt
* @since JDK 1.8
*/
public class PersonServiceProxy implements IPersonService {
private IPersonService personService;
public PersonServiceProxy(final IPersonService personService){
this.personService = personService;
}
public void speak() {
System.out.println("君不见,黄河之水天上来,奔流到海不复回。");
personService.speak();
System.out.println("人生得意须尽欢,莫使金樽空对月。\n" +
"天生我材必有用,千金散尽还复来。\n" +
"烹羊宰牛且为乐,会须一饮三百杯。\n" +
"岑夫子,丹丘生,将进酒,杯莫停。\n" +
"与君歌一曲,请君为我倾耳听。(倾耳听 一作:侧耳听)\n" +
"钟鼓馔玉不足贵,但愿长醉不复醒。(不足贵 一作:何足贵;不复醒 一作:不愿醒/不用醒)\n" +
"古来圣贤皆寂寞,惟有饮者留其名。(古来 一作:自古;惟 通:唯)\n" +
"陈王昔时宴平乐,斗酒十千恣欢谑。\n" +
"主人何为言少钱,径须沽取对君酌。\n" +
"五花马,千金裘,呼儿将出换美酒,与尔同销万古愁。");
}
}
3.3.4、测试
package com.stt.test;
import com.stt.pojo.Person;
import com.stt.service.UserService;
import com.stt.service.impl.PersonService;
import com.stt.service.impl.PersonServiceProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* ClassName: SpringTest
*/
public class SpringTest {
public static void main(String[] args) {
//创建PersonService对象
PersonService personService = new PersonService();
personService.speak();
//创建代理对象
PersonServiceProxy personServiceProxy = new PersonServiceProxy(personService);
personServiceProxy.speak();
}
}
3.3.5、静态代理总结
?优点:可以做到在符合开闭原则的情况下对目标对象进行功能扩展。
?缺点:我们得为每一个服务都得创建代理类,工作量太大,不易管理。同时接口一旦发生改变,代理类也得相应修改。
3.4、动态代理
3.4.1、特点
?1、不需要生成实现接口
?2、使用JDK的API在内存中构建代理对象
3.4.2、代理类
package com.stt.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* PersonService代理对象
*/
public class PersonServiceProxy implements InvocationHandler {
//业务类对象
private Object target;
public PersonServiceProxy(Object target){
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
System.out.println("invoke开始");
result = method.invoke(target,args);
System.out.println("invoke结束");
return result;
}
}
3.4.3、测试
package com.stt.test;
import com.stt.pojo.Person;
import com.stt.proxy.PersonServiceProxy;
import com.stt.service.IPersonService;
import com.stt.service.UserService;
import com.stt.service.impl.PersonService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Proxy;
/**
* ClassName: SpringTest
*/
public class SpringTest {
public static void main(String[] args) {
//被代理对象
PersonService personService = new PersonService();
//代理对象
PersonServiceProxy serviceProxy = new PersonServiceProxy(personService);
//获取类加载器
ClassLoader classLoader = personService.getClass().getClassLoader();
//获取该类的接口
Class<?>[] interfaces = personService.getClass().getInterfaces();
IPersonService iPersonService = (IPersonService)Proxy.newProxyInstance(classLoader, interfaces, serviceProxy);
iPersonService.speak();
}
}
3.4.4、总结
?1、实现InvocationHandler接口重写invoke方法
?2、创建代理对象使用Proxy类的newProxyInstance方法,传入实现类类加载器,接口和代理类的对象
不错记得三连哦,收藏等于学会,还不快快收藏!
相关推荐
- 《每日电讯报》研发数字工具,教你更有效率地报道新闻
-
为鼓励新闻编辑部持续创新,《每日电讯报》正在尝试有战略地研发数字工具。网站的数字媒体主任马尔科姆o科尔斯(MalcolmColes)表示,《每日电讯报》正试图去“创建一些可持续资产”,以便于让记者们...
- html5学得好不好,看掌握多少标签
-
html5你了解了多少?如果你还是入门阶段的话,或者还是一知半解的话,那么我们专门为你们收集的html5常用的标签大全对你就很有帮助了,你需要了解了html5有哪些标签你才能够更好的。驾驭html5...
- 前端分享-少年了解过iframe么(我想了解少年)
-
iframe就像是HTML的「内嵌画布」,允许在页面中加载独立网页,如同在画布上叠加另一幅动态画卷。核心特性包括:独立上下文:每个iframe都拥有独立的DOM/CSS/JS环境(类似浏...
- 做SEO要知道什么是AJAX(人能看到但搜索引擎看不到的内容)
-
一个明显的,人能看到但搜索引擎不能看到的内容是AJAX。那么什么是AJAX呢?其实,了解过的基本上也都清楚,AJAX不是新的编程语言,而是一种使用现有标准的新方法。AJAX最大的优点是在不重新加...
- 介绍最前沿的人工智能创新,‘无反向传播’神经网络训练方法?
-
图像由GoogleImageFX生成前言:本文整理自NoProp原始论文与实践代码,并结合多个公开实现细节进行了全流程复现。对神经网络训练机制的探索仍在不断演进,如果你也在研究反向传播之...
- 说说我们对HTML6的期许(对html的看法)
-
HTML5概述HTML5是HTML语言最受欢迎的版本之一,它支持音频和视频、离线存储、移动端、和标签属性等等。还提供了article,section,header这样的标签来帮助开发者更好...
- 浏览器中在线预览pdf文件,pdf.mjs插件实现web预览pdf
-
背景:本来只是淘宝上卖卖袜子,想着扩展一下业务,准备做同名“来家居”海外袜子馆外贸项目,碰到pdf在线预览的需求,就找了pdf.js插件进行实践后把此方法记录下来,可以通过多种方法来实现,每种方法都有...
- SVG 在前端的7种使用方法,你还知道哪几种?
-
本文简介点赞+关注+收藏=学会了技术一直在演变,在网页中使用SVG的方法也层出不穷。每个时期都有对应的最优解。所以我打算把我知道的7种SVG的使用方法列举出来,有备无患~如果你还...
- HTML5常用标签大全(html5em标签)
-
HTML前端开发最终取决于掌握标签的多少HTML大概有七八百个标签楼主这里给大家总结了下HTML常用标签标签描述<!--...-->定义注释。<!DOCTYPE>定义文档类型...
- "伪君子Snoop Dogg!"... WHAT?| MetroDaily 24/7
-
TUE.01-新作品-虽说年纪大了会有点糊涂,但是最近SnoopDogg的这波操作实在是让粉丝们有点迷,甚至有人表示没想到他是这样的"伪君子"......而这一切都源于他近日在IG上Po出的一...
- 莎夏·班克斯盼望表哥Snoop Dogg为其作出场曲
-
NXT女子冠军莎夏·班克斯(SashaBanks)近日接受了迈阿密先驱报采访,访谈纪要如下:关于她出众的形象:“我一向喜欢与众不同。为了能让人眼前一亮,我的装束总是非常前卫、非常抢眼,这样才能让观众...
- 喜欢Snoop!全球第一间「史努比博物馆」海外分馆在东京!
-
1950年起,由美國漫畫家CharlesM.Schulz創作的作品《Snoopy》史努比,其鮮明的可愛角色與幽默的劇情內容,至今仍成為許多大朋友與小朋友心中的最愛。為了紀念作者所設立的全球首...
- Vetements 推出 Snoop Dogg 肖像「天价」T-Shirt
-
Vetements的CEOGuramGvasalia早前才透露品牌经营策略的秘密–Vetements如何成为人人热议的话题品牌。但似乎他仍有更多需要解释的东西–这个法国奢侈品牌最新...
- 狗爷Snoop Dogg的《I Wanna Thank Me》巡回演唱会旧金山站
-
西海岸匪帮说唱歌手SnoopDogg在《IWannaThankMe》巡回演唱会旧金山站表演(图片来自ICphoto)西海岸匪帮说唱歌手SnoopDogg(图片来自ICphoto)西海...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- maven镜像 (69)
- undefined reference to (60)
- zip格式 (63)
- oracle over (62)
- date_format函数用法 (67)
- 在线代理服务器 (60)
- shell 字符串比较 (74)
- x509证书 (61)
- localhost (65)
- java.awt.headless (66)
- syn_sent (64)
- settings.xml (59)
- 弹出窗口 (56)
- applicationcontextaware (72)
- my.cnf (73)
- httpsession (62)
- pkcs7 (62)
- session cookie (63)
- java 生成uuid (58)
- could not initialize class (58)
- beanpropertyrowmapper (58)
- word空格下划线不显示 (73)
- jar文件 (60)
- jsp内置对象 (58)
- makefile编写规则 (58)