我的应用程序结构就像我创建了一个注释如下:-@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface SampleAnnotation {}然后创建了一个示例拦截器: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; }}然后我创建了一个 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 }}我的拦截功能开始执行之前执行sampleMethod()的SampleClassForInterceptor类,然后执行后sampleMethod()再次回来拦截,现在我在这里有一段代码,将插入的结果(这是我们从得到sampleMethod())。这是我得到的地方NullPointerException,我检查了代码,发现该SampleService对象没有被注入,它的值是null注意:我正在使用具有 RESTFUL 服务概念的微服务
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
当我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);
}
}
添加回答
举报
0/150
提交
取消