[Logo]
Forums Register Login
Problem with @Resource annotation (without web.xml)
Hello Tomcat Users!

Recently I've bumped into following problem with @Resource annotation. I am using Tomcat 6.0.24 and wanted to use the DataSource from JNDI in my application.

It means that I've configured the resource on server level:

server.xml


In web.xml I've got the resource referenced like this:



And my servlet class looks like this (imports omitted intentionally):



As you can see I've used the @Resource annotation instead of looking for the resource in JNDI context, as it seems much more developer-friendly for me.

At this point, everything works fine - the resource is located and "Everything is ok!" is printed out.

What bothers me, is the Servlet specification (15.5.4):

This annotation [@Resource] is equivalent to declaring a resource-ref, message-destination-ref or env-ref, or resource-env-ref element in the deployment descriptor.


Therefore I should be able to delete the "resource-ref" part from the web.xml which is redundant and base only on @Resource in servlet class, which seems to sound definitely more reasonable. Unfortunately if I do that, the lookup error occurs:

SEVERE: Allocate exception for servlet myTest
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context


I've tested it on Tomcat 6.0.24 and 7.0. Is it proper Tomcat reaction and did I misunderstand the Servlet specification or am I doing something wrong?

Thanks in advance for replies!

Cheers,
Pedro
Welcome to the JavaRanch, Pedro!

Tomcat6 shouldn't be expected to honor the annotation-based web.xml configuration options. It predates them. Tomcat7 does - I think. But I have a beta version of Tomcat 7 sitting on my desktop waiting for a free nanosecond to install and evaluate it, so I don't know.
Hi Tim!

Thanks for your answer.

The thing is, that Tomcat 6.0.24 is working fine with @Resource annotation, because as far as I remember it's a part of Servlet 2.5 and not Servlet 3.0 annotation.

It just stops working if you delete the web.xml "resource-ref" part, but the thing you've said could be an explanation.

However, it still harrows me why it is not working with Tomcat 7. Maybe it's my misunderstanding of the specification, and the web.xml "resource-ref" part is still obligatory?

Cheers!
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Oct 23, 2017 11:49:37.