Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Inject data source in application running on Tomcat  RSS feed

 
Stephan van Hulst
Saloon Keeper
Posts: 7927
143
  • 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: 7927
143
  • 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.
 
Thisara Deshan
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: 7927
143
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!