views:

198

answers:

4

I'm using GlassFish v3. The following field is declared in a class:

@Resource
private javax.sql.DataSource _data_source;

The following is declared in web.xml:

<data-source>
  <name>java:app/env/data</name>
  <class-name>com.mysql.jdbc.Driver</class-name>
  <server-name>localhost</server-name>
  <port-number>3306</port-number>       
  <user>myUser</user>                           
  <password>myPass</password>
</data-source>

At run-time _data_source is empty. What am I doing wrong?

+1  A: 

Could you try this:

@Resource(lookup = "java:app/env/data")
private DataSource _data_source;

See also

Pascal Thivent
I already tried adding lookup, with no luck. The class containing the declaration is a Server Authentication Module as specified by JSR 196. I'm not sure if that makes a difference or not.
Andrew
A: 

In addition to Pascal's answer: If injection via annotations doesn't work (no Exception occurs, the fields are just null), the problem is often an old deployment descriptor version. For Glasfish v3, you can use:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"&gt;
Chris Lercher
I think that the OP is using a Servlet 3.0 `web.xml` or he wouldn't be able to specify a [Datasource Definition](http://blogs.sun.com/enterprisetechtips/entry/datasource_resource_definition_in_java) in the deployment descriptor.
Pascal Thivent
My fault, I posted the wrong descriptor... (updated now) But you're right, probably it wouldn't even work to specify the data-source element with the wrong descriptor version. However, I've experienced a similar problem, when trying to inject @EJBs in GFv3: An old descriptor version disabled injection completely.
Chris Lercher
My understanding is that GlassFish relies on the DD version to "activate" services so having a "wrong" version might result in unexpected behavior indeed. But I wonder if injection can work without the lookup attribute when using Datasource definition (assuming you are using the appropriate naming convention for the attribute name).
Pascal Thivent
The web.xml was created by NetBeans 6.8 and looks the same as the one you posted above Chris.
Andrew
A: 

Something like this should work, no xml:

@Resource(name="jdbc/__default")
private DataSource ds
...
Connection con = null {
try {
  con = ds.getConnection();
  ...
} finally {
  if (con != null) con.close()
}
natros
Which is exactly NOT what the OP wants... The OP wants to leverage datasource definition.
Pascal Thivent
Yes, I would like to define the database connection parameters in an xml file, so I can change them easily if necessary.
Andrew
A: 

Try using @Resource(lookup="java:app/env/data") private DataSource _data_source;

Jagadish Prasath