Initialcontext in a standalone Java program

前端 未结 6 1433
傲寒
傲寒 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 15:06

    Here is an example adapted from the accepted answer but doing everything inline to avoid creating extra classes.

    public static void main(String[] args) {
        setupInitialContext();
        //do something that looks up a datasource
    }
    
    private static void setupInitialContext() {
        try {
            NamingManager.setInitialContextFactoryBuilder(new InitialContextFactoryBuilder() {
    
                @Override
                public InitialContextFactory createInitialContextFactory(Hashtable environment) throws NamingException {
                    return new InitialContextFactory() {
    
                        @Override
                        public Context getInitialContext(Hashtable environment) throws NamingException {
                            return new InitialContext(){
    
                                private Hashtable dataSources = new Hashtable<>();
    
                                @Override
                                public Object lookup(String name) throws NamingException {
    
                                    if (dataSources.isEmpty()) { //init datasources
                                        MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
                                        ds.setURL("jdbc:mysql://localhost:3306/mydb");
                                        ds.setUser("mydbuser");
                                        ds.setPassword("mydbpass");
                                        dataSources.put("jdbc/mydbname", ds);
    
                                        //add more datasources to the list as necessary
                                    }
    
                                    if (dataSources.containsKey(name)) {
                                        return dataSources.get(name);
                                    }
    
                                    throw new NamingException("Unable to find datasource: "+name);
                                }
                            };
                        }
    
                    };
                }
    
            });
        }
        catch (NamingException ne) {
            ne.printStackTrace();
        }
    }
    

提交回复
热议问题