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

相关文章

Spring 中的切面与事务结合使用完整示例

《Spring中的切面与事务结合使用完整示例》本文给大家介绍Spring中的切面与事务结合使用完整示例,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录 一、前置知识:Spring AOP 与 事务的关系 事务本质上就是一个“切面”二、核心组件三、完

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

AOP编程的基本概念与idea编辑器的配合体验过程

《AOP编程的基本概念与idea编辑器的配合体验过程》文章简要介绍了AOP基础概念,包括Before/Around通知、PointCut切入点、Advice通知体、JoinPoint连接点等,说明它们... 目录BeforeAroundAdvise — 通知PointCut — 切入点Acpect — 切面

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

C#异步编程ConfigureAwait的使用小结

《C#异步编程ConfigureAwait的使用小结》本文介绍了异步编程在GUI和服务器端应用的优势,详细的介绍了async和await的关键作用,通过实例解析了在UI线程正确使用await.Conf... 异步编程是并发的一种形式,它有两大好处:对于面向终端用户的GUI程序,提高了响应能力对于服务器端应

C# async await 异步编程实现机制详解

《C#asyncawait异步编程实现机制详解》async/await是C#5.0引入的语法糖,它基于**状态机(StateMachine)**模式实现,将异步方法转换为编译器生成的状态机类,本... 目录一、async/await 异步编程实现机制1.1 核心概念1.2 编译器转换过程1.3 关键组件解析

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

Springboot如何正确使用AOP问题

《Springboot如何正确使用AOP问题》:本文主要介绍Springboot如何正确使用AOP问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录​一、AOP概念二、切点表达式​execution表达式案例三、AOP通知四、springboot中使用AOP导出

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实