Guice 学习(八)AOP (面向切面的编程)

2024-05-23 07:08

本文主要是介绍Guice 学习(八)AOP (面向切面的编程),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Guice的AOP还是很弱的,目前仅仅支持方法级别上的,另外灵活性也不是很高。看如下示例:

Guice支持AOP的条件是:

类必须是public或者package (default)
类不能是final类型的
方法必须是public,package或者protected
方法不能使final类型的
实例必须通过Guice的@Inject注入或者有一个无参数的构造函数

且看示例代码

1、定义接口
package com.guice.AOP;import com.google.inject.ImplementedBy;@ImplementedBy(ServiceImpl.class)
public interface Service {public void sayHello();
}
2、定义实现类
package com.guice.AOP;import com.google.inject.Singleton;
import com.google.inject.name.Named;@Singleton
public class ServiceImpl implements Service {@Named("log")@Overridepublic void sayHello() {System.out.println(String.format("[%s#%d] execute %s at %d", this.getClass().getSimpleName(), hashCode(), "sayHello", System.nanoTime()));}
}
3、定义切面
package com.guice.AOP;import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;/***  TODO :自定义的方法拦截器,用于输出方法的执行时间* * @author E468380*/
public class LoggerMethodInterceptor implements MethodInterceptor {@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {String name = invocation.getMethod().getName();long startTime = System.nanoTime();System.out.println(String.format("before method[%s] at %s", name, startTime));Object obj = null;try {obj = invocation.proceed();// 执行服务} finally {long endTime = System.nanoTime();System.out.println(String.format("after method[%s] at %s, cost(ns):%d", name, endTime, (endTime - startTime)));}return obj;}
}
4、测试类
package com.guice.AOP;import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;public class AopTest {@Injectprivate Service service;public static void main(String[] args) {Injector injector = Guice.createInjector(new Module() {@Overridepublic void configure(Binder binder) {binder.bindInterceptor(Matchers.any(), Matchers.annotatedWith(Names.named("log")), new LoggerMethodInterceptor());}});injector.getInstance(AopTest.class).service.sayHello();injector.getInstance(AopTest.class).service.sayHello();injector.getInstance(AopTest.class).service.sayHello();}
}

输出结果:

 before method[sayHello] at 18832801981960[ServiceImpl$$EnhancerByGuice$$d4244950#1109685565] execute sayHello at 18832817170768after method[sayHello] at 18832817378285, cost(ns):15396325before method[sayHello] at 18832817542181[ServiceImpl$$EnhancerByGuice$$d4244950#1109685565] execute sayHello at 18832817640327after method[sayHello] at 18832817781772, cost(ns):239591before method[sayHello] at 18832817920651[ServiceImpl$$EnhancerByGuice$$d4244950#1109685565] execute sayHello at 18832818013023after method[sayHello] at 18832818132657, cost(ns):212006

关于此结果有几点说明:

(1)由于使用了AOP我们的服务得到的不再是我们写的服务实现类了,而是一个继承的子类,这个子类应该是在内存中完成的。

(2)除了第一次调用比较耗时外(可能guice内部做了比较多的处理),其它调用事件为0毫秒(我们的服务本身也没做什么事)。

(3)确实完成了我们期待的AOP功能。



5、切面注入依赖

如果一个切面(拦截器)也需要注入一些依赖怎么办?

在这里我们声明一个前置服务,输出所有调用的方法名称。

①定义接口
package com.guice.AOP;import org.aopalliance.intercept.MethodInvocation;import com.google.inject.ImplementedBy;@ImplementedBy(BeforeServiceImpl.class)
public interface BeforeService {void before(MethodInvocation invocation);
}
②定义实现类
package com.guice.AOP;import org.aopalliance.intercept.MethodInvocation;public class BeforeServiceImpl implements BeforeService {@Overridepublic void before(MethodInvocation invocation) {System.out.println("Before--->" + invocation.getClass().getName());}
}
③定义切面
package com.guice.AOP;import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;import com.google.inject.Inject;//这个切面依赖前置服务
public class AfterMethodIntercepter implements MethodInterceptor {@Injectprivate BeforeService beforeService;@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {beforeService.before(invocation);Object obj = null;try {obj = invocation.proceed();} finally {System.out.println("after--->" + invocation.getClass().getName());}return obj;}
}
④编写测试类
package com.guice.AOP;import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;public class AopTest2 {@Injectprivate Service service;public static void main(String[] args) {Injector injector = Guice.createInjector(new Module() {@Overridepublic void configure(Binder binder) {AfterMethodIntercepter after = new AfterMethodIntercepter();binder.requestInjection(after);binder.bindInterceptor(Matchers.any(), Matchers.annotatedWith(Names.named("log")), after);}});injector.getInstance(AopTest2.class).service.sayHello();}}

输出结果:

 Before--->com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation[ServiceImpl$$EnhancerByGuice$$618294e9#506575947] execute sayHello at 20140444543338after--->com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation

说明
Binder绑定一个切面的API是:

com.google.inject.Binder.bindInterceptor(Matcher<? super Class<?>>, Matcher<? super Method>, MethodInterceptor...)

第一个参数是匹配类,第二个参数是匹配方法,第三个数组参数是方法拦截器。也就是说目前为止Guice只能拦截到方法,然后才做一些切面工作。

注意

尽管切面允许注入其依赖,但是这里需要注意的是,如果切面依赖仍然走切面的话那么程序就陷入了死循环,很久就会堆溢出。
Guice的AOP还是很弱的,目前仅仅支持方法级别上的,另外灵活性也不是很高。

这篇关于Guice 学习(八)AOP (面向切面的编程)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/996165

相关文章

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

C#多线程编程中导致死锁的常见陷阱和避免方法

《C#多线程编程中导致死锁的常见陷阱和避免方法》在C#多线程编程中,死锁(Deadlock)是一种常见的、令人头疼的错误,死锁通常发生在多个线程试图获取多个资源的锁时,导致相互等待对方释放资源,最终形... 目录引言1. 什么是死锁?死锁的典型条件:2. 导致死锁的常见原因2.1 锁的顺序问题错误示例:不同

PyCharm接入DeepSeek实现AI编程的操作流程

《PyCharm接入DeepSeek实现AI编程的操作流程》DeepSeek是一家专注于人工智能技术研发的公司,致力于开发高性能、低成本的AI模型,接下来,我们把DeepSeek接入到PyCharm中... 目录引言效果演示创建API key在PyCharm中下载Continue插件配置Continue引言

四种Flutter子页面向父组件传递数据的方法介绍

《四种Flutter子页面向父组件传递数据的方法介绍》在Flutter中,如果父组件需要调用子组件的方法,可以通过常用的四种方式实现,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录方法 1:使用 GlobalKey 和 State 调用子组件方法方法 2:通过回调函数(Callb

SpringBoot实现动态插拔的AOP的完整案例

《SpringBoot实现动态插拔的AOP的完整案例》在现代软件开发中,面向切面编程(AOP)是一种非常重要的技术,能够有效实现日志记录、安全控制、性能监控等横切关注点的分离,在传统的AOP实现中,切... 目录引言一、AOP 概述1.1 什么是 AOP1.2 AOP 的典型应用场景1.3 为什么需要动态插

C#反射编程之GetConstructor()方法解读

《C#反射编程之GetConstructor()方法解读》C#中Type类的GetConstructor()方法用于获取指定类型的构造函数,该方法有多个重载版本,可以根据不同的参数获取不同特性的构造函... 目录C# GetConstructor()方法有4个重载以GetConstructor(Type[]

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;