关闭

本地配置JNDI数据源(可供以jetty启动的web应用通过查询JNDI调用)

标签: jettyweb服务
405人阅读 评论(0) 收藏 举报

import java.io.File;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class Test2
{
    private final static File currentDir = new File( new File( "" )
    .getAbsolutePath() );

    private static void createJNDIDataSource() throws NamingException
    {
        Properties properties = new Properties();
        properties.setProperty( "java.naming.factory.initial",
                "org.mortbay.naming.InitialContextFactory" );
        Context initialContext = new InitialContext( properties );
        Context springCtx = initialContext.createSubcontext( "jdbc" );

        File f = new File( currentDir.getParentFile(),
                "/build/dev/datasource_bean.xml" );

        ApplicationContext applicationContext = new FileSystemXmlApplicationContext(
                f.getAbsolutePath() );
        springCtx
                .bind( "unicfgext", applicationContext.getBean( "dataSource" ) );
    }
   
    public static void main( String[] args ) throws NamingException
    {
        //创建数据源
        createJNDIDataSource();
        //查找数据源
        Properties properties = new Properties();
        properties.setProperty( "java.naming.factory.initial",
                "org.mortbay.naming.InitialContextFactory" );
        Context initialContext = new InitialContext( properties );
        //通过JNDI查找数据源
        BasicDataSource dataSource = (BasicDataSource)initialContext.lookup( "jdbc/unicfgext" );
        //打印数据源对象
        System.out.println(dataSource);
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:801次
    • 积分:37
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档