I am using HK2 within my Jersey app. To bind classes I am using the inhabitant generator maven plugin.
For one of my classes I need to use a factory to produce an instance. Binding the factory within my application class works as expected:
register(new AbstractBinder() {
@Override
protected void configure() {
bindFactory(ClientManagerFactory.class).to(ClientManager.class);
}
});
The problem is that my inhabitants file is beeing ignored as soon as I register the abstract binder.
How to bind a Factory by annotations (without using a programmatic binder at all?
If this is not possible with HK2: How to use an AbstractBinder
for classes that need a factory, and use the inhabitants file for all others?
Update: My factory looks like this:
public class ClientManagerFactory implements Factory<ClientManager> {
@Override
public ClientManager provide() {
return ClientManager.fromSettings();
}
@Override
public void dispose(ClientManager instance) {
instance.cleanupResources();
}
}
A Factory is a service, and is slightly special because the provide method of the factory is also a service, so one Factory class produces two hk2 services. This means that the Factory itself can be injected with other services. But it also means, when using automatic service discovery (hk2-metadata-generator or hk2-inhabitant-genertor) that you need to annotate it with @Service.
Note that the scope of the Factory and the scope of the provide method can be different. In fact, if you leave any scope annotation off the provide method it will, by default, be in the PerLookup scope. I have modified your code from above to make it a Factory where both the Factory and the provide method service are in the Singleton scope:
@Service
public class ClientManagerFactory implements Factory<ClientManager> {
@Override @Singleton
public ClientManager provide() {
return ClientManager.fromSettings();
}
@Override
public void dispose(ClientManager instance) {
instance.cleanupResources();
}
}
As a side note, when you use @Service the default scope becomes Singleton which is why the provide method (which cannot have @Service on it) is by default in the PerLookup scope. Qualifiers can also be put on the provide method, in which case the service returned by the provide method will be qualified with those qualifiers.