HK2中bindAsContract和bind的区别

Deb*_*yay 4 dependencies bind inject hk2

我正在努力在 J2EE jersey 项目中实现构造函数的依赖注入。我正在使用HK2。我创建一个类

class MyServiceImpl implements MyService{
  @Inject
  public MyServiceImpl(String test){
   // do something
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我的问题是,当我通过扩展 AbstractBinder 在dependencybinder 类中注册此依赖项注入时,将依赖项绑定为简单的“bind”与“bindAsContract”之间有什么区别?

Pau*_*tha 5

当你使用

bind(ServiceImpl.class).to(IService.class)
Run Code Online (Sandbox Code Playgroud)

ServiceImpl是实现类,并且IService是您宣传为注入类型的合同。所以你会使用

@Inject
private IService service;
Run Code Online (Sandbox Code Playgroud)

bindAsContract(ServiceImpl.class)
Run Code Online (Sandbox Code Playgroud)

您是说这ServiceImpl既是实现类是要宣传的合同。所以你需要像这样注入它。

@Inject
private ServiceImpl service;
Run Code Online (Sandbox Code Playgroud)