Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Resource Injection on DataSource throws NullPointerException

 
Debojit Sinha
Ranch Hand
Posts: 66
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm trying to use Resource Injection with Datasource to connect to my database, but when I try to get the conection from the DataSource object, I get a NullPointerException. The JNDI entry is working fine, because I was able to fetch data when I used DataSource with JNDI name lookup, but not using @Resource. Could anybody point out what I'm doing wrong? The complete code is as follows(NullPointerException occurs for lines 21 and 26, and I'm using JDeveloper 11g and WebLogic 10.3.4):

Any suggestion would be much appreciated.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34839
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Debojit,
I assume you are on JEE 5? That version doesn't let you inject resources into random classes; only JEE managed entities. This article is about Oracle's solution, but describes the problem nicely.

I'm going to move your thread to our JEE forum since it more about dependency injection than JDBC.
 
Debojit Sinha
Ranch Hand
Posts: 66
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeanne,
Thanks for the reply, it was most helpful, but in that case, how do I go about abstracting the database connection aspect from the business code? Can you suggest any workaround? The article you mentioned did suggest one (I think), but I couldn't make much sense of it, sorry.
Debojit
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34839
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Debojit Sinha wrote:Hi Jeanne,
Thanks for the reply, it was most helpful, but in that case, how do I go about abstracting the database connection aspect from the business code? Can you suggest any workaround? The article you mentioned did suggest one (I think), but I couldn't make much sense of it, sorry.
Debojit

The article suggests an Oracle specific API. I wasn't proposing you use it; I just like their description of the problem.

Approaches that will work:
1) Use JNDI directly
2) Inject the resource in your servlet/ejb and pass it to your class
3) Use Spring .

I personally favor #1 over #2. You can still have a separate factory class that abstracts the InitialContext/JNDI logic from your business class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic