@Resource annotation is null at run-time
I'm using GlassFish v3. The following field is declared in a class:
@Resource
private javax.sql.DataSource _data_source;
The foll开发者_Go百科owing 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?
Could you try this:
@Resource(lookup = "java:app/env/data")
private DataSource _data_source;
See also
- DataSource Resource Definition in Java EE 6
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">
Try using:
@Resource(lookup="java:app/env/data")
private DataSource _data_source;
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()
}
精彩评论