NoAspectBoundException error in class constructor of AspectJ class with Dependency Injection

北慕城南 提交于 2019-12-12 02:18:41

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/37293827/noaspectboundexception-error-in-class-constructor-of-aspectj-class-with-dependen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!