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

相关文章

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. 完整代码实

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen