gpt4 book ai didi

java - 使用定制工厂 HK2 DI 和 Jersey

转载 作者:行者123 更新时间:2023-11-30 03:45:06 28 4
gpt4 key购买 nike

我在 Jersey 应用程序中使用 HK2 容器。我需要使用自定义工厂方法从 HK2 容器获取注入(inject)的实例。例如,

// Here I declare the IOC binding.
public class ApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bind(Logger.class).to(ILogger.class).in(Singleton.class);;
bind(MySqlRepository.class).to(IRepository.class).in(Singleton.class);
}
}



public class MyApplication extends ResourceConfig {
public static ApplicationBinder binder ;
public MyApplication () {
binder = new ApplicationBinder();
register(binder);
packages(true, "com.myapplication.server");
}
}

这是我的代码:

public class BusinessLogic

{
//@Inject
//ILogger logger ;

//Instead
ILogger logger = DependencyResolver .resolve(ILogger.class) // resolve will get ILogger from HK2 container
}

我需要这样做的原因是有时,我手动分配具有依赖关系的类,因此这样每次使用@Inject都会返回null。例如,如果我使用 new BusinessLogic() ,则带有 @Inject 的记录器为 null。我还必须绑定(bind)业务逻辑并使用 IOC 才能获取 ILogge。

我需要这样的东西:

public class DependencyResolver {    

public static <T> T resolve(Class<T> beanClass){
return instance;
}
}

我需要使用 DependencyResolver 才能获取我在 MyApplication 中注册的实例。

任何建议。提前致谢...

最佳答案

我不是 100% 确定你到底想做什么,但是......

我认为您误解了 AbstractBinder.bind(...) 或绑定(bind)本身。另外,afaig 您无法将某些内容注入(inject)到不是托管组件的实例中(例如您的 BusinessLogic )。

参见jersey.java.net - ioc有关您的 BusinessLogic 的示例。您可以查看 ComponentProvider 和/或 InjectableProvider

对于您的 ILogger,我建议创建并绑定(bind)一个像这样的工厂:

public class LoggerFactory implements Factory<ILogger> {

// inject stuff here if you need (just an useless example)
@Inject
public LoggerFactory(final UriInfo uriInfo) {
this.uriInfo = uriInfo;
}

@Override
public ILogger provide() {
// here you resolve you ilogger
return MyLocator.resolve(ILogger.class);
}

@Override
public void dispose(ILogger instance) {
// ignore
}

}

绑定(bind)工厂

public class ApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bindFactory(LoggerFactory.class).to(ILogger.class).in(PerLookup.class /* or other scopeAnnotation if needed */);

// what's you Logger.class ?
// bind(Logger.class).to(ILogger.class).in(Singleton.class);
// bind(MySqlRepository.class).to(IRepository.class).in(Singleton.class);
}
}

希望这对您有所帮助。也许有人愿意为您的案例写一些有关提供者的内容。

关于java - 使用定制工厂 HK2 DI 和 Jersey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953055/

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