我已经想出了一种方法,但这基本上是一种黑客行为。ContainerRequestContext
您可以尝试从 中显式获取ContainerRequestContext
实例ServiceLocator
,并在上下文超出请求范围时处理异常,而不是注入。
public class MyObject {
private final Optional<ContainerRequestContext> containerRequestContext;
@Inject
public MyObject(ServiceLocator serviceLocator) {
this.containerRequestContext = getContainerRequestContext(serviceLocator);
}
private Optional<ContainerRequestContext> getContainerRequestContext(ServiceLocator serviceLocator) {
try {
return Optional.of(serviceLocator.getService(ContainerRequestContext.class));
} catch (MultiException e) {
if (e.getCause() instanceof IllegalStateException) {
return Optional.empty();
} else {
throw new ExceptionInInitializerError(e);
}
}
}
}
然后可以更进一步并创建自己的OptionalContainerRequestContext
类型。
public class OptionalContainerRequestContext {
private final Optional<ContainerRequestContext> containerRequestContext;
@Inject
public OptionalContainerRequestContext(ServiceLocator serviceLocator) {
this.containerRequestContext = getContainerRequestContext(serviceLocator);
}
public ContainerRequestContext get() {
return containerRequestContext.get();
}
public boolean isPresent() {
return containerRequestContext.isPresent();
}
private Optional<ContainerRequestContext> getContainerRequestContext(ServiceLocator serviceLocator) {
try {
return Optional.of(serviceLocator.getService(ContainerRequestContext.class));
} catch (MultiException e) {
if (e.getCause() instanceof IllegalStateException) {
return Optional.empty();
} else {
throw new ExceptionInInitializerError(e);
}
}
}
}
然后你可以绑定它:
bind(OptionalContainerRequestContext.class).to(OptionalContainerRequestContext.class);
然后在需要的地方注入它:
public class MyObject {
private final OptionalContainerRequestContext optionalContainerRequestContext;
@Inject
public MyObject(OptionalContainerRequestContext optionalContainerRequestContext) {
this.optionalContainerRequestContext = optionalContainerRequestContext;
}
}