[JAVA] properties설정

승카이·2023년 11월 24일
0

JAVA

목록 보기
1/1
post-thumbnail

JAVA 웹 프로젝트에서 properties파일 활용하기

properties 파일 생성

Properties파일은 한 라인에 key=value 형식으로 작성.
.properties 확장자를 붙여 저장.

key = value
db.server = localhost
db.user = admin
db.passwod = admin
db.driverclass = dbclass

web.xml에 properties파일 경로 설정

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/application-context.properties</param-value>
</context-param>

프로퍼티 사용하는 부분

Java파일에서 사용 시

public class MyServlet extends HttpServlet {
 
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext sc = req.getServletContext();
        Properties properties = new Properties();
        properties.load(new FileReader(sc.getRealPath(sc.getInitParameter("contextConfigLocation"))));
 
        for (Object object: properties.keySet()) {
            System.out.println(object + " = " + properties.get(object));
        }
    }
}

Spring설정 파일에서 사용 시

<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
    <property name="driverClass" value="${db.driverclass}"/>
    ...
</bean>

컨텍스트 파라미터는 ServletContext 객체의 getInitParameter() 메소드로 값을 꺼낼 수 있다.

profile
Hello World!

0개의 댓글