【发布时间】:2015-11-27 10:38:00
【问题描述】:
在我的 JSF 托管 bean (HomePageController.java) 中,我尝试使用 @Resource 注释获取数据库连接,但由于某种原因它仍然是 null,在调试时我发现它提供了 NullPointerException。
我正在使用 Tomcat 8 服务器。这可能是因为 Tomcat 8 不是功能齐全的 Java EE 容器吗?
我已经在 META-INF/context.xml 文件中定义了数据源
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/ministore-jsf-mvc">
<!-- PostgreSQL Datasource -->
<Resource auth="Container" driverClassName="org.postgresql.Driver"
factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
maxActive="50" maxIdle="10" maxWait="-1"
name="jdbc/ministore-db" password="postgres"
type="javax.sql.DataSource"
url="jdbc:postgresql://db-server:5432/ministore-db" username="postgres"/>
</Context>
web.xml sn-p
<!-- DB configuration (using Datasource) -->
<resource-ref>
<description>PostgreSQL Datasource</description>
<res-ref-name>jdbc/ministore-db</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
HomePageController.java
@ManagedBean
@RequestScoped
public class HomePageController implements Serializable {
private static final Logger LOG = Logger.getLogger(HomePageController.class);
@Resource(name = "jdbc/ministore-db")
protected DataSource dataSource;
public Product getProduct() {
LOG.debug("Into the HomePageController...");
//get the Product object based on productId parameter
Product product = null;
try {
product = new MasterDao(dataSource).getProduct(DEFAULT_PRODUCT_ID);
LOG.debug("product = " + product);
} catch (Exception e) {
LOG.error("Exception while getting product from DB for productId = " + DEFAULT_PRODUCT_ID);
LOG.error(e.getMessage());
}
LOG.debug("product = " + product);
return product;
}
}
输出:
DEBUG com.ministore.controllers.HomePageController - Into the HomePageController...
ERROR com.ministore.controllers.HomePageController - Exception while getting product from DB for productId = 101
ERROR com.ministore.controllers.HomePageController -
DEBUG com.ministore.controllers.HomePageController - product = null
【问题讨论】:
-
据我所知,Tomcat 没有为您提供任何 CDI 支持 - 您包含哪些库以使用 CDI? (我试过一次,但没有运气。)
-
我在 pom.xml 中使用
javaee-web-api库和provided范围。奇怪的是@Resource与 servlet 一起工作。 -
您是否尝试过使用 JNDI api 手动查找资源?如果你能做到这一点,那么它就是在搞砸的容器。否则,您的配置/代码有问题
-
是的,我尝试使用 JNDI api 手动查找资源并且成功了。