• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Inject data source in application running on Tomcat  RSS feed

 
Bartender
Posts: 9494
184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm running a Servlet 3.0 application on Tomcat, using Jersey to create REST controllers and Weld for dependency injection. My controllers use repositories and my repositories use a data source.

I've configured my application so that Tomcat puts the data source into the web application context. When I look up the data source with JNDI, I can get an instance of DataSource just fine:

Now, instead of looking up the data source from the initial context, I want to inject it into the constructors of my repository:

Weld manages to find my DataSourceUserRepository when I try to inject it into my UserController, but it can't satisfy the DataSource dependency:

It doesn't matter when I change the name to "java:comp/env/jdbc/ExampleDB", "ExampleDB", "exampleDB" or when I remove the annotation altogether.

Here is my context.xml:

Does anyone know how I can fix this?
 
Stephan van Hulst
Bartender
Posts: 9494
184
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, so I finally figured it out:

Sadly, @Resource doesn't perform constructor injection, but I'll take what I can.

It took me quite some time to figure out the exact dependencies I needed. I'll share my POM here for those who want Servlet 3.0 + Tomcat + Weld + Jersey + Jackson.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Option
Screenshot-(23).png
[Thumbnail for Screenshot-(23).png]
 
Stephan van Hulst
Bartender
Posts: 9494
184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch Thisara,

Thanks. I had managed to get the resource into my context and access it through InitialContext, the problem was how to inject it into my constructor using Weld. The @Resource annotation sadly isn't allowed on constructors.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!