spring 설정 xml과 소스코드에서 properties 사용하기

spring 설정 xml에 다음과 같은 구문을 추가한다.

(첫번째)

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/mvc 

      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd

      http://www.springframework.org/schema/beans 

      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

      http://www.springframework.org/schema/context 

      http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="com.tutorialspoint" />

 

 <!-- context:property-placeholder location="classpath:database.properties"  /!-->

<context:property-placeholder location="/WEB-INF/*.properties" />

굵은 표시를 한 부분을 추가한다.

classpath:database.properties의 의미는 classpath로 지정된 경로들에 있는 database.properties를 읽어오라는 뜻이라한다.

classpath:properties/*.properties의 의미는 classpath로 지정된 경로들에 있는 확장자가 properties인 파일들을 모두 읽어 오라는 뜻이라한다.

 

난 /WEB-/INF/database.properties,/WEB-/INF/file.properties  2개의 properties를 넣어서

 

<context:property-placeholder location="/WEB-INF/*.properties" />  이렇게 사용하였다.

주의할 점은 properties들에 같은 key 값이 있다면 원하지 않는 데이터가 읽힐수 있다고 한다. 그럴 경우 다른 방법을 사용해야한다고 한다.

 

spring 설정 xml에 추가로 다음과 같이 db연결 정보를 변경한다.

 

(두번째)

 

 기존코드

     <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="cubrid.jdbc.driver.CUBRIDDriver" />
        <property name="url"
            value="jdbc:cubrid:localhost:30000:springdemo:::?charset=UTF-8" />
        <property name="username" value="dba" />
        <property name="password" value="admin" />
    </bean> <!-- Definition for studentJDBCTemplate bean -->
   

 신규코드

     <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

 

 

(세번째)

database.properties

jdbc.driver=cubrid.jdbc.driver.CUBRIDDriver
jdbc.url=jdbc:cubrid:localhost:30000:springdemo:::?charset=UTF-8
jdbc.username=dba
jdbc.password=admin

 

file.properties

file_dir.url=/static/file_upload_data/
file_dir.thumbnail.url=/static/file_upload_data/thumbnail/
file_dir.english_word_audio_file.url=/static/english_word_audio_file/

 

(네번째)

자바 코드에서 해당 properties 값을 가져다 쓸때는 아래와 같이 했다.

@Value("${file_dir.url}")
private String fileUploadLoc;

속성으로 지정해야했다. 지역변수로는 annotation을  이용해서는 받아올수 없었다.

properites에 해당 키값이 없다면 컴파일시에 오류를 낸다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

위에 내용은 내가 메인으로 사용할 properties의 내용을 가져올때 사용할 방법이다.

나혼자 만들때는 문제가 안되겠지만 혹시나 나중에 다른사람들과 협업을 할때를 고려하여 다른 방법도 적는다.

 

SpEL이용

(첫번째)

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

 

<util:properties id="db" location="/WEB-INF/database.properties" />

<util:properties id="file" location="/WEB-INF/file.properties" />

위에 굵게 표시한 부분을 넣어줘야한다.

주의 할점은  첫번째와는 다르게 <util:properties id="db" location="/WEB-INF/*.properties" /> 이렇게

사용할수가 없다. 에러가 발생한다.   파일명을 온전히 써주어야한다.

 

(두번째)

 

 

이전코드

   <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

 신규코드

 <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="#{db['jdbc.driver']}" />
       <property name="url" value="#{db['jdbc.url']}" />
       <property name="username" value="#{db['jdbc.username']}"  />
       <property name="password" value="#{db['jdbc.password']}"  />
         </bean> <!-- Definition for studentJDBCTemplate bean --> 

 

 

(세번째 properties 설정은 동일하다.)

(네번째) 소스코드에서 사용할때

    @Value("#{file['file_dir.url']}")
    private String fileUploadLoc;

소스코드에서 사용할때 첫번째 것은 동일한 key가 두개이상 존재할때 내가 원하는 값을 선택할수 없는 문제가 있고.

두번째것은 값이 실제로 존재하지 않아도 오류를 내지않고 null로 들어가게 된다.

 

두방법을 모두 한꺼번에 사용해도 에러가 발생되지 않는다.

단 두번째 방법을 사용하고 spring 설정 xml에 첫번째 방법의 태그를 지우고

첫번째 방법과 같이

@Value("${file_dir.url}")
private String fileUploadLoc;

쓰게 되면 fileUploadLoc에는 "${file_dir.url}"  라는 문자열이 들어가게 된다. 조심해야한다.

 

JSP에서 properties 읽기(펌 : http://nkjava.blogspot.in/2013/07/springmvc-read-property-in-jsp.html)

Spring config
<util:properties id="db" location="/WEB-INF/database.properties" />
jsp
<spring:eval expression="@db.getProperty('jdbc.password')" />

테스트 해보니까 SpEL만 되는 것 같다.  참고 자료에는 context:property-placeholder 태그도 사용했지만

없어도 정상동작 하는 것을 확인하였다.

 

 

[출처] https://jijs.tistory.com/m/entry/spring-설정-xml과-소스코드에서-properties-사용하기

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
35 [EMF] EMF Tutorial EMF 튜터리얼 file 졸리운_곰 2023.08.23 283
34 Eclipse RAP Tutorial for Beginners - Workbench Application (OLD) file 졸리운_곰 2021.01.30 323
33 Learn Eclipse GMF in 15 minutes file 졸리운_곰 2019.11.27 253
32 [Eclipse] GEF entry series (10, an implementation of the form) file 졸리운_곰 2019.11.25 212
31 GEF Programmer Guide 번역 졸리운_곰 2019.11.25 227
30 Learn Eclipse GMF in 15 minutes file 졸리운_곰 2019.11.20 224
29 RCP 에디터 정리 졸리운_곰 2019.11.20 333
28 다른 그림과 관련하여 GEF 편집기 레이아웃에서 그림의 위치 제한 조건을 동적으로 계산 Dynamically calculating the position constraints for a figure in a GEF editor layout in relation to another figure file 졸리운_곰 2019.11.20 277
27 RCP 등에서 .mf 파일로 다른 프로젝트 익스포트 포함시 라이브러리(메소드)를 찾지 못할 때, Eclipse RCP - cant resolve importing libraries in final build file 졸리운_곰 2019.10.15 410
26 ESE2006-EclipseModelingSymposium15_GMF.pdf file 졸리운_곰 2019.09.21 302
25 GMF_Creation_Review.pdf file 졸리운_곰 2019.09.21 366
24 Eclipse EMF and GMF Tutorial file 졸리운_곰 2019.09.21 222
23 GMF Tutorial/ko file 졸리운_곰 2019.09.20 347
22 Model Driven Architecture approach to domain of graphical editors file 졸리운_곰 2019.09.20 268
21 Single_Sourcing_RAP_RCP_en.pdf file 졸리운_곰 2019.05.15 311
20 Rich client platform 설명 및 배우기 참고 졸리운_곰 2019.05.15 309
19 Rich Ajax Platform, Part 1: 소개 file 졸리운_곰 2019.05.15 320
18 또 하나의 크로스 플랫폼: Eclipse RAP file 졸리운_곰 2019.05.15 319
17 Eclipse 4 RCP 튜토리얼(완료) file 졸리운_곰 2019.05.14 977
16 Updating UI in Eclipse RCP 졸리운_곰 2015.11.07 408
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED