美文网首页
[Guice] 7 Guice Aop

[Guice] 7 Guice Aop

作者: LZhan | 来源:发表于2019-08-13 23:16 被阅读0次

Guice中的Aop,通常是结合自定义注解实现。

以实现一个日志打印的切面注解为例:
1、自定义注解

@Retention(RetentionPolicy.RUNTIME)
public @interface Logged {
}

2、在module中实现绑定


image.png

第一个参数:作用在哪些class上
第二个参数:哪些class会执行(标有对应注解的才执行)
第三个参数:MethodIntercaptor接口实现类

bindInterceptor(Matchers.any(),
                Matchers.annotatedWith(Logged.class),
                new MethodInterceptor() {
                    @Override
                    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
                        Method method = methodInvocation.getMethod();
                        System.out.println("Hello World");
                        return methodInvocation.proceed();
                    }
                });

3、当在第三个参数MethodIntercaptor接口实现类中想要某个注入的成员变量

public class LoggerInterceptor implements MethodInterceptor {

    @Inject @Output private  String message;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Method method = methodInvocation.getMethod();
        System.out.println(message);
        return methodInvocation.proceed();
    }
}

使用到了一个@Output的注入变量,那么在绑定时,要加上requestInjection(loggerInterceptor);

LoggerInterceptor loggerInterceptor=new LoggerInterceptor();
requestInjection(loggerInterceptor);
        
bindInterceptor(Matchers.any(),
              Matchers.annotatedWith(Logged.class),
              loggerInterceptor
                );

注意:
guice的Aop必须使用在通过guice创建的对象上,比如我们手工创建一个对象,添加日志AOP,这时,guice也是没有办法去拦截的,必须通过guice从头开始inject开始的才可以进行AOP处理

相关文章

  • [Guice] 7 Guice Aop

    Guice中的Aop,通常是结合自定义注解实现。 以实现一个日志打印的切面注解为例:1、自定义注解 2、在modu...

  • Guice AOP(Matcher)

    本教程主要详细讲解Guice的一些AOP方式,通过该简单教程让我们可以快速使用Guice进行AOP开发,后续我们会...

  • Java Vert.x 集成Guice

    Java Vert.x 集成Guice Guice介绍 Guice是谷歌推出的一个轻量级依赖注入框架,帮助我们解决...

  • Druid(二)——Druid中用到的一些技术

    Guice框架 Guice是Google开发的一个轻量级的DI框架,Guice在2008年获得了软件界的奥斯卡--...

  • 3.Guice轻量级注解Guice简单之美

    Guice[https://github.com/google/guice]是谷歌推出的一个轻量级依赖注入框架,帮...

  • Guice

    「Guice」依赖注入框架中的小清新单例情况下轻量级的DI呗。

  • Google Guice(一) 初识Guice

    翻译自官方文档,能力有限,如有缺漏,还望指正。 把所有的代码都糅合到一起,这可能是开发过程中最让人觉得无聊和枯燥的...

  • Druid源码阅读——Server启动流程

    Druid的代码里面使用了大量的Google Guice依赖注入(DI),还是第一次接触Guice。相比于Spri...

  • Guice简介

    Guice是什么Guice(读作Juice)是Google开发的一套注入框架,目前最新版本是4.0Beta。注入的...

  • [Guice] 1 初识'juice'

    1、Guice is a lightweight dependency injection framework f...

网友评论

      本文标题:[Guice] 7 Guice Aop

      本文链接:https://www.haomeiwen.com/subject/gebijctx.html