如何使用 Guice 将必要的对象注入 AspectJ 方面

4ev*_*one 1 java aop dependency-injection aspectj guice

有没有办法在我有一个方面必须在其逻辑中使用一些复杂的实例化服务的情况下使用 Guice 和 AspectJ ?

例如:

@Aspect
public class SomeAspect {

  private final ComplexServiceMangedByGuice complexServiceMangedByGuice;

  @Inject
  public SomeAspect(ComplexServiceMangedByGuice complexServiceMangedByGuice){
    this.complexServiceMangedByGuice = complexServiceMangedByGuice;
  }

  @AfterThrowing(value = "execution(* *(..))", throwing = "e")
  public void afterThrowingException(JoinPoint joinPoint, Throwable e){
    complexServiceMangedByGuice.doSomething(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试像示例中那样(使用方面构造函数),我的方面将不会被调用。如果我尝试注入字段(没有定义方面构造函数),方面将被调用,但字段complexServiceMangedByGuice不会被设置。我发现的一个解决方案是在建议方法主体中获取实例,因此一个方面将如下所示:

@Aspect
public class SomeAspect {

private static ComplexServiceManagedByGuice complexServiceManagedByGuice;

  @AfterThrowing(value = "execution(* *(..))", throwing = "e")
  public void afterThrowingException(JoinPoint joinPoint, Throwable e){
    if(complexServiceManagedByGuice == null){
    Injector injector = Guice.createInjector(new ModuleWithComplexService());
    complexServiceMangedByGuice = injector.getInstance(ComlexServiceManagedByGuice.class);
    }
    complexServiceMangedByGuice.doSomething(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

但这会带来一些不良的开销。

zAl*_*bee 6

您可以像这样注释方面类的字段:

@Inject
SomeDependency someDependency
Run Code Online (Sandbox Code Playgroud)

然后要求 Guice 通过在 Guice 模块的方法中写入以下内容来将依赖项注入到您的方面类中configure()

requestInjection(Aspects.aspectOf(SomeAspect.class));
Run Code Online (Sandbox Code Playgroud)

文档requestInjection说:

成功创建后,注入器将注入给定对象的实例字段和方法

来源: https: //github.com/jponge/guice-aspectj-sample