我的應(yīng)用程序結(jié)構(gòu)就像我創(chuàng)建了一個(gè)注釋如下:-@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface SampleAnnotation {}然后創(chuàng)建了一個(gè)示例攔截器:public class SampleInterceptor implements MethodInterceptor { private static final Logger logger = LoggerFactory.getLogger(SampleInterceptor.class); @Inject SampleService sampleService; // this is not working public Object invoke(MethodInvocation invocation) throws Throwable { logger.info("SampleInterceptor : Interceptor Invoked"); Object result = invocation.proceed(); Observable<List<Sample>> observable = (Observable<List<Sample>>) result; SampleSender sender = null; List<Sample> sampleList = observable.toBlocking().first(); for(Sample sample : sampleList ) { sender = new SampleSender(); sender.setBoolean(sample.isBoolean()); logger.info("Pushing Data into Sender"); sampleService.insert(String.join("_", "key", "value"), sender); // here getting NullPointerException because sampleService is null } return result; }}然后我創(chuàng)建了一個(gè) GuiceModule 如下:-public class SampleModule extends AbstractModule { @Override protected void configure() { bindInterceptor(Matchers.any(), Matchers.annotatedWith(SampleAnnotation.class), new SampleInterceptor());}}我在其中使用上述注釋的類是// This class also have so many method and this was already declared and using in another services, I created a sample class hereclass SampleClassForInterceptor { // this sampleMethod() is not a new method, its already created, // now I am adding annotation to it, because after finishing this functionality, // I want something should be done, so created annotation and added here }}我的攔截功能開(kāi)始執(zhí)行之前執(zhí)行sampleMethod()的SampleClassForInterceptor類,然后執(zhí)行后sampleMethod()再次回來(lái)攔截,現(xiàn)在我在這里有一段代碼,將插入的結(jié)果(這是我們從得到sampleMethod())。這是我得到的地方NullPointerException,我檢查了代碼,發(fā)現(xiàn)該SampleService對(duì)象沒(méi)有被注入,它的值是null注意:我正在使用具有 RESTFUL 服務(wù)概念的微服務(wù)
1 回答

桃花長(zhǎng)相依
TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
當(dāng)我requestInjection在SampleModule,然后SampleService被注入攔截器即我修改SampleModule代碼如下
public class SampleModule extends AbstractModule {
@Override
protected void configure() {
SampleInterceptor interceptor = new SampleInterceptor();
requestInjection(interceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(SampleAnnotation.class), interceptor);
}
}
添加回答
舉報(bào)
0/150
提交
取消