我正在从泽西岛1.19迁移到泽西岛2.25。我找不到足够的文档来替换InjectableProvider
有人能帮我吗。
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.glassfish.hk2.api.InjectionResolver;
import org.springframework.stereotype.Component;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
@Provider
@Component
public class LocaleProvider extends AbstractHttpContextInjectable<Locale>
implements InjectionResolver<Context, Type> {
private final Locale swedish = new Locale("sv", "", "");
@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
@Override
public Injectable<Locale> getInjectable(ComponentContext ic, Context a, Type c) {
if (c.equals(Locale.class)) {
return this;
}
return null;
}
@Override
public Locale getValue(HttpContext c) {
final List<Locale> locales = c.getRequest().getAcceptableLanguages();
if (locales.isEmpty()) {
return Locale.US;
}
for (Locale locale : locales) {
if (locale.getLanguage().equals(swedish.getLanguage())) {
return swedish;
} else if (locale.getLanguage().equals(Locale.US.getLanguage())) {
return Locale.US;
}
}
// return english if no other supported language is found
return Locale.US;
}
}
最佳答案
使用HK2 Factory
。一个帮助程序抽象类是AbstractContainerRequestValueFactory
,它使您可以轻松访问ContainerRequest
。您可以从中获得可接受的语言
public class LocaleFactory
extends AbstractContainerRequestValueFactory<Local> {
@Override
public Locale provide() {
ContainerRequest cr = getContainerRequest();
}
}
然后,您需要注册它。如果您使用的是
ResourceConfig
,则可以执行public AppConfig extends ResourceConfig {
public AppConfig() {
register(new AbstractBinder() {
@Override
public void configure() {
bindFactory(LocalFactory.class)
.to(Locale.class).in(RequestScoped.class);
}
});
}
}
也可以看看:
Dependency injection with Jersey 2.0