반응형
import javax.naming.NamingException;
 
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
 
public class JndiDatasourceCreator {
  private static final Logger LOGGER = LoggerFactory.getLogger(JndiDatasourceCreator.class);
 
  private static final String username = "userName";
  private static final String password = "password";
  private static final String jndiName = "DB_Name";
  private static final String driverClassName = "Driver Name";
  private static final String url = "jdbc://localhost:port/dbName";
  public static BasicDataSource dataSource;
 
  public static void create() throws Exception {
    try {
      final SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
      dataSource = new BasicDataSource();
      dataSource.setUsername(username);
      dataSource.setPassword(password);
      dataSource.setDriverClassName(driverClassName);
      dataSource.setUrl(url);
      builder.bind("java:comp/env/jdbc/" + jndiName, dataSource);
      builder.activate();
    } catch (NamingException ex) {
      LOGGER.info(ex.getMessage());
    }
  }
}



보통 개발환경에서는 JNDI 를 사용하지 않는데 JNDI를 테스할 경우에는 위의 코드를 이용해서 JNDI 환경에서 잘 동작하는지 테스트 할 수 있다.


    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>


<필요한 라이브러리>

반응형

+ Recent posts