I have an AspectJ class using annotation @Aspect in my Java program and I would like to make a class constructor with an injection using @Inject to an interface class but it gave me error of NoAspectBoundException such as follow:
de.hpi.cloudraid.exception.InternalClientError: org.aspectj.lang.NoAspectBoundException: Exception while initializing de.hpi.cloudraid.service.MeasurementAspect: java.lang.NoSuchMethodError: de.hpi.cloudraid.service.MeasurementAspect: method <init>()V not found
Here is the snippet of my class:
@Aspect
public class MeasurementAspect {
private final RemoteStatisticService remoteStatisticService;
@Inject
public MeasurementAspect(RemoteStatisticService remoteStatisticService) {
this.remoteStatisticService = remoteStatisticService;
}
....
}
I tried to use normal injection like private @Inject RemoteStatisticService remoteStatisticService; but it gave me error of NullPointerException.
Any help is appreciated. Thanks
Aspects are not candidates for dependency injection, so you'll have to work around this limitation. They're also instantiated by the aspectj runtime, and not CDI, and you can't take control of their instantiation.
What you can do is, create a separate class which is handled by the CDI container and inject the aspect's dependencies into this helper class instead. Then set up your aspect's dependencies from this helper class manually. You can mark this helper class as a startup singleton, so that it runs at startup after it's dependencies can be satisfied.
You could use a startup singleton helper bean similar to this one:
@Singleton
@Startup
public class MeasurementAspectSetup {
@Inject
private RemoteStatisticService remoteStatisticService;
@PostConstruct
private void setupAspect() {
Aspects.aspectOf(MeasurementAspect.class).
setRemoteStatisticService(this.remoteStatisticService);
}
}
Of course, you would have to add the setter for the RemoteStatisticService
to the aspect, or change the field's visibility in the aspect and set it directly. You'll also need to remove the parametric constructor from the aspect so a default no-arg constructor is available.