---
title: "手动建立jetty datasource "
author: "nbaertuo"
date: "2009-05-14T19:27:08Z"
tags: []
slug: "jetty-datasource"
draft: false
lastmod: "2009-05-14T23:13:06Z"
id: 387015
url: "https://nbaertuo.iteye.com/blog/387015"
---

看了jetty官方的datasource建立代码 需要在web/inf下面新建一个jetty-env.xml。但是这种方式只适合在整个项目有完整的war包情况下，才能顺利加载，如果你的项目是个多工程的，而且webapp目录还没有生成或者web.xml是编译期生成的，那么你不不能适合这种方式。 在前面的文章中介绍了手动使用jetty嵌入加载web工程，这里给个手动设置jndi datasource的代码例子。

 

 

 /\** * 绑定datasource到JNDI \*/

private void bindDataSource()

{

   DriverManagerDataSource dataSource = new DriverManagerDataSource();         

   dataSource.setDriverClassName("org.hsqldb.jdbcDriver");

   dataSource.setUrl("jdbc:hsqldb:mem:booking");

   dataSource.setUsername("sa");

   dataSource.setPassword("");

   javax.naming.Context context;

   try {

          context = new InitialContext();

          javax.naming.Context compCtx = (javax.naming.Context) context.lookup("java:comp");    

           javax.naming.Context envCtx = compCtx.createSubcontext("env"); NamingUtil.bind(envCtx, 

                                   "jdbc/hsqldb", dataSource); }

   catch (NamingException e)

            { e.printStackTrace();

 

       }

}

 

 

 

spring中使用jndi &lt;!-- jndi test--&gt;

&lt;bean id="dataSourceJNDI" class="org.springframework.jndi.JndiObjectFactoryBean"&gt;

      &lt;property name="jndiName"&gt;&lt;value&gt;java:comp/env/jdbc/hsqldb&lt;/value&gt;&lt;/property&gt;

&lt;/bean&gt;