猿问

使用 Guice 框架编写基于注解的方法拦截器时无法注入 java 对象

我的应用程序结构就像


我创建了一个注释如下:-


@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 here

class 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 服务概念的微服务


泛舟湖上清波郎朗
浏览 129回答 1
1回答

桃花长相依

当我requestInjection在SampleModule,然后SampleService被注入拦截器即我修改SampleModule代码如下public class SampleModule extends AbstractModule {&nbsp; &nbsp; &nbsp;@Override&nbsp; &nbsp; &nbsp;protected void configure() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SampleInterceptor interceptor = new SampleInterceptor();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;requestInjection(interceptor);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bindInterceptor(Matchers.any(), Matchers.annotatedWith(SampleAnnotation.class), interceptor);&nbsp; &nbsp; &nbsp;}}
随时随地看视频慕课网APP

相关分类

Java
我要回答