使用druid配置jndi


1.druid.jar、mysql.jar放到%tomcat_home%\lib下

2.%tomcat_home%\conf下配置context.xml配置如下

<Context>

<Resource name="UserDatabase" auth="Container"

              type="org.apache.catalina.UserDatabase"

              description="User database that can be updated and saved"

              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"

              pathname="conf/tomcat-users.xml" />


<Resource 

         name="jdbc/MysqlDataSource"

         factory="com.alibaba.druid.pool.DruidDataSourceFactory"

         auth="Container"

       type="javax.sql.DataSource"

       driverClassName="com.mysql.jdbc.Driver"

      url="jdbc:mysql://localhost:3306/basicpool?useUnicode=true&amp;characterEncoding=utf-8"

        username="root"

     password="root"

        maxActive="50"

      maxWait="10000"

         removeabandoned="true"

       removeabandonedtimeout="60"

        logabandoned="false"

filters="stat"/>


</Context>


如果是jdbc获取jndi数据源

/**

 * @ClassName: JdbcUtil

 * @Description: Jdbc连接工具类

 * @author  Iverson

 *

 */

public class JdbcUtil {


    private static final String MYSQL_DB_JNDINAME="java:comp/env/jdbc/MysqlDataSource";

private static DruidDataSource dsMysql;

static {

   try {

                //1.初始化名称查找上下文

       Context ctx= new InitialContext();

           //2.通过JNDI名称知道到DataSource

       dsMysql=(DruidDataSource) ctx.lookup(MYSQL_DB_JNDINAME);

       

        } catch (Exception e) {

        e.printStackTrace();

        }

}


/**

* 获取connection

* @return 

* @throws Exception

*/

public static Connection getConnection()throws Exception{

   return dsMysql.getConnection();

}

}



如果是spring配置

<!-- 引入外部文件 -->

<context:property-placeholder location="classpath:jdbc.properties" />

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">

<property name="jndiName" value="${jndiName}"/>

</bean>

<!-- 事务 -->

<bean id="transactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<!-- 开启事务注解 -->

<tx:annotation-driven transaction-manager="transactionManager"/>


jdbc.properties

jndiName=java:comp/env/jdbc/MysqlDataSource




你可能感兴趣的:(JNDI,druid,JNDI数据源)