본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

이론

이름기반으로 검색한다, JNDI

JNDI (Java Naming and Directory Interface)
일종의 중개자

JNDI API를 사용하여 이름기반으로 데이터 리소스등을 검색하고 사용할 수 있다.

데이터연결정보를 애플리케이션 코드내에 하드코딩하지않고 연결정보를 외부에서 관리하는것등의 방법.

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class JNDIExample {
    public static void main(String[] args) {
        try {
            // JNDI 컨텍스트 생성
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");

            // DataSource 생성
            DataSource dataSource = createDataSource();

            // JNDI에 DataSource 등록
            envContext.bind("jdbc/myDataSource", dataSource);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static DataSource createDataSource() throws NamingException {
        // 프로퍼티 파일 로드
        Properties properties = new Properties();
        InputStream inputStream = JNDIExample.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // DataSource 생성 및 설정
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(properties.getProperty("db.driver"));
        dataSource.setUrl(properties.getProperty("db.url"));
        dataSource.setUsername(properties.getProperty("db.username"));
        dataSource.setPassword(properties.getProperty("db.password"));

        return dataSource;
    }
}
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mydatabase
db.username=myusername
db.password=mypassword