为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

泛舟湖上清波郎朗 2021-12-30 17:13:31
我的应用程序结构就像我创建了一个注释如下:-@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);

     }

}


查看完整回答
反对 回复 2021-12-30
  • 1 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信