Continuation of topic Jersey 2 + HK2 - @ApplicationScoped not working.
I already know, how to bind classes in order to @Inject
them properly.
Do you have any ideas, how to automize this process? Putting every single service in bind
statements seems like very bad smell in my application.
I Have a sugestion that solved my problem here, i've tried proposed solution and not worked here. In my solution it's necessary annotate each class with @MyInjectable annotation.
1-Create an Annotation
2-Create a AbstractBinder implementation
3-Create a ResourceConfig
4-Configure properly in web.xml
I would suggest first looking here: Automatic Service Population.
The basic process is to use @Service annotations on your classes and use the JSR-269 (APT) processor (Metadata Generator) at build time. Doing so will add some metadata to your jar files (normally under META-INF/hk2-locator/default).
You can then make sure these services get picked up automatically rather than having to do all those pesky binds by using a Populator which you get from the Dynamic Configuration Service which is available in every ServiceLocator.
The pseudo-code would be something like this:
In the above code the ClasspathDescriptorFileFinder is used to search through the classpath to find the metadata. Other strategies could be used in environments like OSGi.
IMO this is a much better way to add services rather than doing all the binds by yourself.
After using Google's Guice for a number of years, I am accustomed to the availability of a Just-In-Time binder, allowing the injection of arbitrary types without requiring any upfront configuration.
I too found the idea of having to explicitly bind every service to be a bad code smell. I'm also not crazy about the need to use a special build step and the added initialization code for the populator.
So I came up with the following
JustInTimeResolver
implementation:With this in my project, I simply added the following to my binder in my Jersey application configuration:
and I get automatic binding creation like I did in Guice.