我有这段代码来提供自定义可注射对象:
config.register(new AbstractBinder() {
@Override
protected void configure() {
delegatorFactory = ...; //custom factory to delegate to
bindFactory(new Factory<Object>() {
@Inject
private Provider<ContainerRequestContext> req;
@Override
public void dispose(Object arg0) {
}
@Override
public Object provide() {
// req is needed but is null
}
}).to(delegatorFactory.getType()).in(RequestScoped.class);
}
});
不幸的是,正如provide()中的注释所揭示的那样,req
字段在执行时不会被注入(我需要该位置的ContainerRequestContext
)。
我错过了什么让它像这样工作,即注入工厂的字段?
答案 0 :(得分:1)
用课程绑定它。大多数时候,当你自己开始实例化时,你会失去注射的好处。所以只需使用一个类
bindFactory(YourFactoryClass.class)
要让进样器手动注入工厂,您可以使用Feature
public class YourFeature implements Feature {
@Override
public void configure(FeatureContext context) {
final ServiceLocator locator = ServiceLocatorProvider.getLocator(context);
locator.inject(anyObject);
context.register(new YourAbstractBinder());
}
}
config.register(new YourFeature());