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

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
18 [java 인공지능] Spring AI 로 ChatGPT API 만들기 졸리운_곰 2024.12.30 214
17 [java 인공지능] 오라클, 자바 머신러닝 라이브러리 ‘트리뷰오’ 오픈소스로 공개 졸리운_곰 2023.08.27 296
16 [java 인공지능] 자바를 위한 머신 러닝 라이브러리 졸리운_곰 2023.08.27 360
15 [Java 인공지능] 오라클, 자바 머신러닝 라이브러리 ‘트리뷰오’ 오픈소스로 공개 file 졸리운_곰 2023.08.13 358
14 [java 인공지능] [java] 라이프 게임 (life game) file 졸리운_곰 2021.10.19 337
13 How to use Weka in your Java code 졸리운_곰 2020.02.01 307
12 weka and java eclipse example : A Simple Machine Learning Example in Java file 졸리운_곰 2020.01.31 362
11 머신러닝? weka file 졸리운_곰 2020.01.31 357
10 [Weka] Weka를 이용한 Iris 데이터 머신러닝 file 졸리운_곰 2020.01.30 363
9 [강좌] WEKA 사용법 (간단한 분류, 의사결정트리 분석 설명) file 졸리운_곰 2020.01.30 343
8 [JESS] Jess , 이클립스 연동 file 졸리운_곰 2019.12.22 215
7 Jess 간단한 문법 요약 졸리운_곰 2019.12.22 277
6 Jess 6.1 다운로드 friedman-hill_src_1_jess_se file 졸리운_곰 2019.12.22 184
5 java artificial intelligence Rule Engine Jess Working Memory 졸리운_곰 2019.12.22 300
4 Defining Functions in Jess 졸리운_곰 2019.12.22 389
3 Jess Language Basics 졸리운_곰 2019.12.22 272
2 Embedding Jess in a Java Application 졸리운_곰 2019.12.22 298
1 다섯개의 탑 자바로 머신러닝 라이브러리 Top 5 machine learning libraries for Java file 졸리운_곰 2017.08.22 388
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED