How can I spoof a jndi lookup for a datasource without a app server

后端 未结 3 1337
别跟我提以往
别跟我提以往 2021-02-04 18:24

I want to test some new functionality which is part of an internal web app. This new code uses a database connection normally provided by an app server (tomcat).

I do no

3条回答
  •  长发绾君心
    2021-02-04 18:38

    With the help of Spring SimpleNamingContextBuilder and Apache BasicDataSource, you can do something like this (I usually have this in a static block in test classes that need JNDI):

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(db_driver_name);
    dataSource.setUrl(db_connection_url);
    dataSource.setUsername(db_username);
    dataSource.setPassword(db_password);
    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    builder.bind(jndi_name, dataSource);
    builder.activate();
    

    The value of jndi_name might look like this: java:comp/env/jdbc/my-db

    Once this is set up, code that normally looks up the database connection via JNDI should work. The code above would for example work with this Spring config:

    
      
    
    

提交回复
热议问题