Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Inject data source in application running on Tomcat  RSS feed

 
Saloon Keeper
Posts: 9134
172
  • 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
Saloon Keeper
Posts: 9134
172
  • 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
Saloon Keeper
Posts: 9134
172
  • 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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!