1

ジャージーに AuthDynamicFilter を登録するときにオブジェクトを注入する方法を理解しようとしています。

public class CustomApplication extends Application<Configuration> {
   public void run(Configuration configuration, Environment environment) throws Exception {
      ...

      environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));   
      ...
   }
}

CustomAuthFilter

@PreMatching
public class CustomAuthFilter<P extends Principal> extends AuthFilter<String, P> {
   private final Object identity;

   @Context
   private HttpServletRequest httpServletRequest;

   @Context
   private HttpServletResponse httpServletResponse;

   public LcaAuthFilter(Identity identity) {
     this.identity = identity;
   }

   @Override
   public void filter(ContainerRequestContext requestContext) throws IOException {
       ...identity.process(httpServletRequest)
   }

}

CustomAuthFilter の作成時に Identity オブジェクトを挿入する方法がないため、上記のコードはコンパイルされません。

あなたが行くなら:

   environment.jersey().register(new AuthDynamicFeature(new CustomerAuthFilter(new Identity())));

この場合、httpServletRequest は null に設定されます。

これを回避する方法を理解できる唯一の方法は、AuthDynamicFeature を使用することさえせず、通常のフィルターを使用してその方法で注入することです。AuthDynamicFeature をどのように使用するのか疑問に思っています。

私はまだdropwizardとjerseyに慣れていないので、ご容赦ください. 私が混乱しているかもしれないいくつかの概念。

どんなアドバイスでも感謝します、ありがとう、デレク

4

1 に答える 1

0

まさにそれを行うアプリがあります。コンストラクターに次の注釈を付け@Injectます。

@PreMatching
public class CustomAuthFilter<P extends Principal> extends AuthFilter<String, P> {
   private final Identity identity;

   @Context
   private HttpServletRequest httpServletRequest;

   @Context
   private HttpServletResponse httpServletResponse;

   // Annotate the ctor with @Inject
   @Inject
   public LcaAuthFilter(Identity identity) {
     this.identity = identity;
   }

   @Override
   public void filter(ContainerRequestContext requestContext) throws IOException {
       ...identity.process(httpServletRequest)
   }

}

Jersey の依存性注入メカニズムに、指定identityした値を注入するように指示します。

Identity identity = getTheIdentity();
environment.jersey().register(new AbstractBinder() {
    @Override
    protected void configure() {
        bind(identity).to(Identity.class);
    }
});
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));

identityが実行時にしか分からない場合は、Supplier<Identity>代わりに a を使用します (コンストラクターも調整します)。

Supplier<Identity> identity = getTheIdentitySupplier();
environment.jersey().register(new AbstractBinder() {
    @Override
    protected void configure() {
        bind(identity).to(new TypeLiteral<Supplier<Identity>>(){});
    }
});
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));
于 2020-05-05T18:58:59.890 に答える