티스토리 뷰

jsp에서 springboot에서 사용하는 설정파일 (application.yml, application.properties)의 값을 바로 가지고 올 수 있다.

 

application.properties (or application.yml) 파일은 다음과 같이 정의가 되어 있는 상황이다. 

oing.daddy=cool guy

이 값을 jsp에서 바로 가지고 와서 사용하고 싶다. 가지고 오는 방법은 다음과 같다. 

 

1. @environment.getProperty 를 통해 가져오는 방법

<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<spring:eval var="oindDaddy" expression="@environment.getProperty('oing.daddy')" />
${oingDaddy}

위와 같이 spring tag를 선언해주고 spring:eval 을 통해서 값을 가지고 올 수 있다. @environment.getProperty 를 통해 properties 파일 (or yml 파일) 의 key 값을 넣어주면 var로 정의한 변수에 값이 담긴다. 다른 설정이 필요없어서 간단하게 사용할 수 있는 장점이 있다. properties, yml 모두 잘 된다. 

 

2. custom properties (or yml) 파일로부터 값을 가져오는 방법

<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<spring:eval var="oingDaddy" expression="@customProperties['oing.daddy']" />
${oingDaddy}

이 방법은 1번의 방식과 동일한 목적을 가지면서도 다른 목적이 있을수도 있다. 바로 spring property로 관리되지 않는 custom property를 만들고 그곳으로부터 값을 가지고 올때 사용할 수 있다. 여기 3번째줄에 사용된 @customProperties는 내가 생성한 bean의 이름이다. 생성한 bean은 다음과 같다. 

@Configuration
public class PropertiesConfig {
	
    @Bean
    public PropertiesFactoryBean customProperties() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource("custom/custom.properties"));
        return bean;
    }
}

이렇게 custom/custom.properties 파일을 읽는 역할을 하는 customProperties bean을 만들고 jsp에서는 @customProperties['key값'] 와 같은 형식으로 가지고 올 수 있다. 테스트를 해보니 yml에 있는 내용도 잘 가지고 온다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30