2

I used this code for accessing database connection through jndi lookup.

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource datasource = (DataSource)envContext.lookup("TestDB");
Connection connection = datasource.getConnection();

It was working fine. Later I replaced this with annotation to do same thing with following code.

@Resource(name="TestDB")
DataSource datasource;

methodName(){
if(datasource!=null){
Connection connection = datasource.getConnection();}
else{
   System.out.println("Datasource is null");
     }
    }

But I got "DataSource is null". I also tried with @Resource(lookup="TestDB") but still getting "DataSource is null". Why datasource is null?

Manmohan
  • 146
  • 1
  • 6
  • Do you use a dependecy injection engine correctly, e.g. is your class created by Spring or do you call an injector to inject annotated properties? – Martin Strejc Sep 20 '13 at 06:38
  • I used @Resource throughout a project that worked on Tomcat 6 and it all stopped working on Tomcat 7. Had to go back to the old code. Never found out why. – user207421 Sep 20 '13 at 07:00
  • I think you need to run TomEE. – Thufir Mar 11 '15 at 15:25

1 Answers1

0

My problem was as described in this comment: https://stackoverflow.com/a/19530417/1494996

The lookup with InitialContext was working, and lookup with @Resourse was not. Once I moved my @Resource declaration to my servlet class from a regular java class, it all started working. The container (Tomcat 8 in my case) was only inspecting well-known components for annotations

kasyak
  • 1
  • 1