bindFactory 不注入字段
bindFactory does not inject fields
我有此代码来提供自定义可注入对象:
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
)。
我缺少什么让它像这样工作,即注入工厂的字段?
用class绑定它。大多数时候,当你开始自己实例化东西时,你就失去了注入的好处。所以只需使用 class
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());
我有此代码来提供自定义可注入对象:
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
)。
我缺少什么让它像这样工作,即注入工厂的字段?
用class绑定它。大多数时候,当你开始自己实例化东西时,你就失去了注入的好处。所以只需使用 class
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());