【发布时间】:2023-03-11 14:30:01
【问题描述】:
我在我的 Jersey 应用程序中使用 HK2 容器。我需要使用我的自定义工厂方法从 HK2 容器中获取注入的实例。 例如,
// 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 的记录器为空。我还必须绑定业务逻辑并使用 IOC 才能获得 ILogge。
我需要这样的东西:
public class DependencyResolver {
public static <T> T resolve(Class<T> beanClass){
return instance;
}
}
我需要使用 DependencyResolver 来获取我在 MyApplication 中注册的实例。
任何建议。 在此先感谢...
【问题讨论】:
-
您是否尝试构建一个 org.glassfish.hk2.api.Factory 以满足您的需求?
-
我做了,但我需要使用我在 ResourceConfig 中使用 ApplicationBinder 进行的绑定配置。
-
请提供更多信息,即代码。您到底尝试将 ILogger 注入到您的存储库中是什么? Repository 是如何参与的——它是否绑定在某个地方?
-
请看我编辑的问题。
标签: java jersey-2.0 hk2