在Tomcat Web容器中注入DataSource时@Resource注释不起作用

时间:2017-04-27 13:26:36

标签: jsf-2 jsf-2.2 tomcat8

我正在开发一个小型Web应用程序并使用轻量级Tomcat Web容器8.5.4,JSF 2.2.9和MySql。

在OrdersBean类中,我试图使用@Resource注释来注入DataSource

@ManagedBean(name="orders")
@SessionScoped
public class OrdersBean {

   //resource injection
   @Resource(name="jdbc/tcomdb")
   private DataSource ds;

   public List<Orders> getOrderList() throws SQLException {

       if(ds == null)
           throw new SQLException("Cannot retrieve Data Source ds");

       //get database connection
       Connection con = ds.getConnection();
       //...
   }

但是,Tomcat Web容器不会注入数据源并抛出NullPointerException。

但是,如果我尝试通过上下文查找服务以传统方式获取DataSource对象,那么它可以很好地工作。

//resource injection not working, getting manually.
public OrdersBean() {
    try {
        Context ctx = new InitialContext();
        ds = (DataSource)ctx.lookup("java:comp/env/jdbc/tcomdb");
    } catch (NamingException e) {
        e.printStackTrace();
    }   
}

的web.xml

<resource-ref>
  <description>MySQL Datasource example</description>
  <res-ref-name>jdbc/tcomdb</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

<!-- JSF mapping -->
<servlet>
   <servlet-name>Faces Servlet</servlet-name>
   <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

context.xml中的MySql DataSource配置

<Context>
   <Resource name="jdbc/tcomdb" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="passwd" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/tcomdb"/>
</Context>

我认为自从版本发布以来,依赖注入在Tomcat Web容器中起作用。 6/7,如更改日志中所示:http://tomcat.apache.org/tomcat-7.0-doc/changelog.html

任何人都可以确认吗?如果Tomcat支持那么我的code / config中出错了什么?

另外,我想知道tomcat web容器如何在内部工作以在两种情况下创建DataSource对象:依赖注入和上下文查找?

请解释。

0 个答案:

没有答案
相关问题