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-사용하기

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
27 [java][maven] jar 파일 의존성 한번에 다운로드 maven 사용 졸리운_곰 2023.08.24 192
26 Prometheus + Grafana로 Java 애플리케이션 모니터링하기 file 졸리운_곰 2020.12.17 279
25 Blockchain Implementation With Java Code file 졸리운_곰 2019.06.16 338
24 Java 코드로 이해하는 블록체인(Blockchain) 졸리운_곰 2019.06.16 377
23 순수 Java Application 코드로 Restful api 호출 졸리운_곰 2018.10.10 415
22 WebDAV 구현을 위한 환경 설정 file 졸리운_곰 2017.09.24 268
21 [Java] Apache Commons HttpClient로 SSL 통신하기 졸리운_곰 2017.03.27 784
20 JSoup를 이용한 HTML 파싱 졸리운_곰 2017.03.04 320
19 jsoup을 활용해서 Java에서 HTML 파싱하는 방법 정리 file 졸리운_곰 2017.03.04 579
18 NSA의 Dataflow 엔진 Apache NiFi 소개와 설치 file 졸리운_곰 2017.01.23 630
17 wordpress-java-integration 자바와 워드프레스 통합 졸리운_곰 2016.12.30 298
16 Create New Posts in Wordpress using Java and XMLRpc 졸리운_곰 2016.11.14 268
15 자바로 POST 방식으로 통신하기, java httppost 클래스를 활용한 예제 졸리운_곰 2016.11.14 647
14 [Java]아파치 HttpClient사용하기 file 졸리운_곰 2016.11.14 301
13 Building a Search Engine With Nutch Solr And Hadoop file 졸리운_곰 2016.04.21 435
12 Nutch and Hadoop Tutorial file 졸리운_곰 2016.04.21 391
11 Latest step by Step Installation guide for dummies: Nutch 0. file 졸리운_곰 2016.04.21 305
10 Nutch 초간단 빌드와 실행 졸리운_곰 2016.04.21 681
9 Nutch로 알아보는 Crawling 구조 - Joinc 졸리운_곰 2016.04.21 536
8 A tiny bittorrent library Java: 자바로 만든 작은 bittorrent 라이브러리 file 졸리운_곰 2016.04.20 418
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED