gpt4 book ai didi

java - 如何在 singleton jersey 拦截器中使用 RequestScoped 对象?

转载 作者:行者123 更新时间:2023-11-30 02:41:16 26 4
gpt4 key购买 nike

Jersey 拦截器是在应用程序启动时构建的。因此,它的依赖项(在本例中为 Cipher )被注入(inject)到请求范围之外。

问题是密码是 stateful所以它们应该被注入(inject)到请求范围中。如何做到这一点?

@Provider
@Priority(Priorities.ENTITY_CODER + 1)
public class CryptInterceptor implements ReaderInterceptor, WriterInterceptor {

@Inject @Named("ENC_CIPHER")
private Cipher encryptionCipher;
@Inject @Named("DEC_CIPHER")
private Cipher decryptionCipher;

@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
InputStream inputStream = context.getInputStream();
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, decryptionCipher);
context.setInputStream(cipherInputStream);
return context.proceed();
}

@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
OutputStream outputStream = context.getOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptionCipher);
context.setOutputStream(cipherOutputStream);
context.proceed();
}
}

为每个新请求期待新的 Cipher 就像将它们注入(inject)到 RequestScope 中一样 --

public class BootstrapBinder extends AbstractBinder {
@Override
protected void configure() {
bindFactory(EncCipherFactory.class).to(Cipher.class).named("ENC_CIPHER").in(RequestScoped.class);
bindFactory(DecCipherFactory.class).to(Cipher.class).named("DEC_CIPHER").in(RequestScoped.class);
}
}

现在显然 hk2( Jersey 的 DI)无法在 Singleton 拦截器内注入(inject) RequestScoped 对象。它导致:

java.lang.IllegalStateException: Not inside a request scope.

最佳答案

您需要代理服务。如果不这样做,Jersey 将尝试注入(inject)实际的对象,并且在创建拦截器时没有请求。至于试图使拦截器本身具有请求范围,我不知道。不确定是否可能。

bindFactory(EncCipherFactory.class)
.proxy(true)
.proxyForSameScope(false)
.to(Cipher.class)
.named("ENC_CIPHER")
.in(RequestScoped.class);

对另一个也做同样的事情。但请记住,当您访问它时,它将是一个代理实例,而不是密码实例。

另请参阅:

关于java - 如何在 singleton jersey 拦截器中使用 RequestScoped 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com