我正在使用一个项目,在tomcat 7中访问JNDI
数据源。这是我的META-INF / context.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/ambes" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="root" password=""
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/ANTTestDb"/>
</Context>
这是我的dao类,dataSource通过上下文查找服务成功注入我的类,如下所示:
public class CoffeeDataBase {
private DataSource dataSource;
public CoffeeDataBase() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/ambes");
} catch (Exception e) {
e.printStackTrace();
}
// other methods definition
}
但是当我用这样的@Resourse anotaion替换查找服务时:
@Resource(lookup="java:comp/env/jdbc/ambes")
public class CoffeeDataBase {
private DataSource dataSource;
public CoffeeDataBase() {
}
// other methods definition
}
我得到这样的NullPointerExeption:
java.lang.NullPointerException
at com.ambestephen.dao.CoffeeDataBase.getCoffeeList(CoffeeDataBase.java:63)
at com.ambestephen.controller.ShowCoffees.doGet(ShowCoffees.java:16)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
我也试过@Resource(name="jdbc/ambes")
,但同样的例外!
答案 0 :(得分:1)
Tomcat不支持@Resource注入。因此,您只能在Tomcat中使用上下文查找服务。您还可以使用依赖注入框架spring来注入dataSource,这使您可以使用@Resource anotation。