gpt4 book ai didi

java - Jersey 2.x 依赖注入(inject)

转载 作者:行者123 更新时间:2023-11-30 08:52:38 25 4
gpt4 key购买 nike

您好,我在将以下代码从 jersey 1.x 移至 jersey 2.x 时遇到问题

@Provider
public class LocaleProvider
extends AbstractHttpContextInjectable<Locale>
implements InjectableProvider<Context, Type> {

@Override
public Injectable<E> getInjectable(ComponentContext ic, Context a, Type c) {
if (c.equals(Locale.class)) {
return this;
}

return null;
}

@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}

@Override
public Locale getValue(HttpContext c) {
final Locales locales = c.getRequest().getAcceptableLanguages();
if (locales.isEmpty()) {
return Locale.US;
}
return locales.get(0);
}
}

我也知道 HK2 在 Jersey 2.0 中可用,但我似乎找不到有助于 Jersey 2.0 集成的文档。

最佳答案

如果您要使用 @Context注释,实际上您需要做的就是实现一个 Factory<T> 由您要注入(inject)的类型参数化。您甚至可以将其他标准可注入(inject)对象注入(inject)到 Factory 中,例如 HttpServletRequest , ContainerRequestContext , HttpHeaders除其他外。例如,匹配上面示例中发生的事情

import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.ws.rs.core.HttpHeaders;
import org.glassfish.hk2.api.Factory;

public class LocaleFactory implements Factory<Locale> {

private final HttpHeaders headers;

@Inject
public LocaleFactory(HttpHeaders headers) {
this.headers = headers;
}

@Override
public Locale provide() {
List<Locale> acceptableLanguges = headers.getAcceptableLanguages();

if (acceptableLanguges.isEmpty()) {
return Locale.US;
}

if ("*".equals(acceptableLanguges.get(0).toString())) {
return Locale.US;
}

return acceptableLanguges.get(0);
}

@Override
public void dispose(Locale t) { /* Do nothing */ }
}

然后你需要绑定(bind)工厂。例如在你的 ResourceConfig .您可以在那里设置范围,如 getScope()在你的例子中。目前支持 Singleton , RequestScopedPerLookup (如果未指定,则为默认值)

@ApplicationPath("/api")
public class AppConfig extends ResourceConfig {

public AppConfig() {
packages("packages.to.scan");

register(new AbstractBinder(){
@Override
public void configure() {
bindFactory(LocaleFactory.class).to(Locale.class)
.in(RequestScoped.class);
}
});
}
}

如果您使用的是 web.xml,那么您可以创建一个 Feature并注册 AbstractBinder在那里,作为seen here

之后,你就可以注入(inject)了

@GET
public Response getLocale(@Context Locale locale) {

如果你想使用自定义注解,那么你需要实现一个 InjectionResolver 用于自定义注释。你可以看到一个完整的例子here ,并在 Jersey documentation - Defining Custom Injection Annotation 中阅读更多内容

关于java - Jersey 2.x 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116859/

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