Is there a way to use Guice and AspectJ for situation where i have an aspect which have to use some complex-to-instantiate service in its logic?
For example:
@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);
}
}
If i try having it like in the example (with aspect constructor), my aspect will not be called. If i try injecting field (without aspect constructor defined), aspect will be called but field complexServiceMangedByGuice
won't be set.
One solution i have found is to get instance in advice method body, so an aspect would look like this:
@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);
}
}
But that has some undesirable overhead.