Initialcontext in a standalone Java program

前端 未结 6 1478
傲寒
傲寒 2020-12-13 14:38

I\'m using a JNDI for creating tomcat connection pool. It works great in a web application. I believe the InitialContext is provided by the tomcat server.

Co         


        
6条回答
  •  遥遥无期
    2020-12-13 14:58

    You can create your own Context by sub-classing javax.naming.InitialContext and implementing only a small subset of methods, typically the bind and the lookup methods.

    Then you can create your data source and bind it to your initial context to a specific key. After this you are ready to go and query from any place your JNDI context in your stand-alone Java programme.

    This is the code you can use to create your own context:

    InitialContext initialContext = new InitialContext() {
    
        private Map table = new HashMap<>();
    
        public void bind(String key, Object value) {
            table.put(key, value);
        }
    
        public Object lookup(String key) throws NamingException {
            return table.get(key);
        }
    };
    
    // Activate the initial context
    NamingManager.setInitialContextFactoryBuilder(environment -> environment1 -> initialContext);
    

    Then you can initialise your data source, whichever you choose:

    InitialContext ic = new InitialContext();
    
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    bds.setUrl(url);
    bds.setUsername(username);
    bds.setPassword(password);
    
    ic.bind(jndiPath, bds);
    

    And somewhere else in your code, you can use the existing data source by retrieving it from the JNDI context:

    InitialContext ic2 = new InitialContext();
    DataSource ds = (DataSource) ic2.lookup(jndiPath);
    assertNotNull(ds);
    Connection conn = ds.getConnection();
    assertNotNull(conn);
    conn.close();
    

提交回复
热议问题