0

I have a very simple REST application that exposes a single @GET endpoint. I am able to run jersey and return a string or JSON object just fine. However, I am unable to connect this with my persistence layer. How can I possibly inject by DataSource instance object into every Resource instantiated by Jersey?

Yes, yes I've seen the dozens of answers with either Guice or other InjectionProviders, etc. but I refuse to believe that I can't pass a reference without writing hundreds of lines of unnecessary code.

I tried using something like in the Rest Server :

final ResourceConfig rc = new ResourceConfig().packages(RestPathPing.class.getPackage().getName());
Map<String, Object> customResourceConfigProps = new HashMap<>();
customResourceConfigProps.put("dataSource", dataSource);
rc.addProperties(customResourceConfigProps);  

and then tried getting the ResourceConfig from the @Context but it returns null. I really need a simple short solution since I have the DataSource instance available at Rest server's creation time.

Alex
  • 459
  • 4
  • 16
  • If you want to pass a reference, then Jersey can't create the resource,. You need to create it, and just register resource with Jersey explicitly as an instance. Otherwise there's no magic way for you to "pass a reference" without actually passing as a reference yourself. I am closing this as a duplicate of how to do dependency injection with Jersey. None of the current answers use Guice. They use Jersey's internal DI framework that only requires a few lines of code – Paul Samsotha Jul 14 '16 at 13:36
  • But doesn't this defy the whole point of automatic resource discovery and instantiation as in `new ResourceConfig().packages("pkgName");` ? Any non-trivial Jersey application would want to interact with the DAO layer and that's why I think this is way too much hassle just to pass a reference to an existing DataSource. Also, if someone has 1000 resources then he has to manually instantiate and register each of them? Sounds like an incredible waste of code and time... – Alex Jul 14 '16 at 14:24
  • 1
    That's what dependency injection frameworks are for. It's called Inversion of Control – Paul Samsotha Jul 14 '16 at 14:26
  • Could you recommend a particular lightweight IOC framework that would allow me to do exactly what I need without too much configuring? – Alex Jul 14 '16 at 14:42
  • 1
    Top two answers in the duplicate link use Jersey internal DI framework. All you need is to register an AbstractBinder where you register your servies/daos, and you can simply `@Inject` them into your resources – Paul Samsotha Jul 14 '16 at 14:53
  • Wow, I was actually able to make one complete solution out of the two answers in the provided link. an AbstractBinder is necessary but it's only 1 one-liner method and you can actually bind an instance to a contract. Awesome! Thanks @peeskillet – Alex Jul 14 '16 at 15:17

0 Answers0