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

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
57 [java, spring] Spring에서 request와 response를 JSON format 으로 한번에 로깅하기 file 졸리운_곰 2021.06.18 178
56 [Spring Boot] 2) Springboot OncePerRequestFilter 와 GenericFilterBean의 차이 file 졸리운_곰 2021.06.18 21
55 [Spring boot] [Spring boot] Spring Boot servlet filter 사용하기 졸리운_곰 2021.06.18 17
54 [SpringBoot] Filter(필터) OncePerRequestFilter간단히 사용하기 file 졸리운_곰 2021.06.18 65
53 [Spring boot] Spring boot 에서 Filter 사용하기 졸리운_곰 2021.06.18 18
52 [Spring Boot] 스프링 부트에 필터를 '조심해서' 사용하는 두 가지 방법 졸리운_곰 2021.06.18 140
51 [스프링 배치] java Spring Batch 졸리운_곰 2020.12.16 77
50 MyBatisPagingItemReader.java 졸리운_곰 2020.11.07 82
49 [JPA] 스프링 데이터 JPA 소개 file 졸리운_곰 2020.11.07 23
48 Spring Batch Example 3 - 청크 지향 프로세싱 file 졸리운_곰 2020.10.24 51
47 Spring Batch Example 2 - 간단한 Job만들기 file 졸리운_곰 2020.10.24 15
46 Spring Batch Example 1 - Spring Batch란? file 졸리운_곰 2020.10.24 55
45 [spring batch] Spring batch Job 설정과 실행하기 file 졸리운_곰 2020.10.24 24
44 public class MyBatisPagingItemReader<T> extends AbstractPagingItemReader<T> { 졸리운_곰 2020.10.23 97
43 public class MyBatisBatchItemWriter<T> implements ItemWriter<T>, InitializingBean { 졸리운_곰 2020.10.23 119
42 MyBatisPagingItemReader, MyBatisPagingItemWriter 졸리운_곰 2020.10.23 208
41 [spring batch] 처음 해보는 Spring batch, Tasklet 작성하기 file 졸리운_곰 2020.10.18 15
40 Spring Boot - Properties 사용법 정리 졸리운_곰 2020.10.15 94
» spring 설정 xml과 소스코드에서 properties 사용하기 졸리운_곰 2020.10.15 14
38 Spring Batch 간단 정리 Sprong Batch 기초를 알아보자 file 졸리운_곰 2020.10.13 47
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED