Notice
Recent Posts
Recent Comments
Link
관리 메뉴

데브마우스

[Spring] DriverManagerDataSource의 DB 아이디와 암호가 적힌beans 설정 파일 분리 방법 본문

Spring/Spring: 정리

[Spring] DriverManagerDataSource의 DB 아이디와 암호가 적힌beans 설정 파일 분리 방법

데브마우스 2024. 2. 13. 12:07

DB 아이디와 암호가 적힌 파일을 분리해야하는 이유

GitHub처럼 원격 저장소에 소스코드를 올려서 소스코드를 백업합니다. 하지만 데이터베이스의 아이디와 암호가 GitHub에 업로드되어서는 안되겠지요?

 

그렇다면 Maven으로 생성한 스프링 프로젝트에서 파일을 분리하는 방법에 대해 알아보도록 하겠습니다.

beans 설정 파일 분리 방법

1. appServlet 폴더 안에 database-context.xml 파일을 생성합니다.

2. database-context.xml 파일 안에 아래와 같은 코드를 작성해주세요.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
   xmlns="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:beans="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <!-- DB 사용을 위한 Bean 객체 설정 -->
   <beans:bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <beans:property name="driverClassName"
         value="com.mysql.cj.jdbc.Driver" />
      <beans:property name="url"
         value="jdbc:DB접속URL" />
      <beans:property name="username" value="DB아이디" />
      <beans:property name="password" value="DB비밀번호" />
   </beans:bean>

   <beans:bean id="jdbcTemplate"
      class="org.springframework.jdbc.core.JdbcTemplate">
      <beans:property name="dataSource" ref="dataSource" />
   </beans:bean>

</beans:beans>

 

3. web.xml의 <servlet> 태그의 <param-value>를 아래처럼 수정해주세요.

   <!-- Processes application requests -->
   <servlet>
      <servlet-name>appServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>
            /WEB-INF/spring/appServlet/servlet-context.xml
            /WEB-INF/spring/appServlet/database-context.xml
         </param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>

4. .gitignore 파일을 수정합니다.

# DB beans
database-context.xml

.gitignore 파일에 위 코드를 추가합니다.

이제 데이터베이스 접속을 다루는 DriverManagerDataSource 클래스가 담긴 database-context.xml 파일은 git에 스테이징되지 않습니다.