Language/Spring 기초

프로퍼티 파일에서 변수값 가져오기

띵큐 2024. 8. 7. 08:42

# 개념

# property 가져오는 문제 해결
1. src/main/resource 폴더에 application.properties 파일이 있어야 하고

app.name=MySpringApp
app.version=1.0
app.yourself=babo

2. servelet-context.xml 파일에서 이 부분이 있어야 value 가져오는 어노테이션이 작동한다.
    <!-- 프로퍼티 파일 로딩 : 이거 넣고 컨트롤러에서 어노테이션으로 프로퍼티 파일 정보를 가져 오게 됨 -->
    <context:property-placeholder location="classpath:application.properties"/>

 

3. HomeController.java

   @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    @Value("${app.yourself}")
    private String appYourself;

    
    //@GetMapping("/info") // spring 4.3부터 사용가능
    //@ResponseBody
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public String getAppInfo() {
        StringBuilder info = new StringBuilder();
        System.out.println("App Name: " + appName + ", Version: " + appVersion + ", App yourself: " + appYourself );
        // 클래스패스에서 프로퍼티 파일의 경로를 로드
        
        org.springframework.core.io.Resource resource = new ClassPathResource("application.properties");
        try {
            URL url = resource.getURL();
            info.append("Property file location: ").append(url.toString());
        } catch (IOException e) {
            info.append("Error loading property file location: ").append(e.getMessage());
        }

        return info.toString();

 

폴더 이미지

 

4. 참고 web.xml

<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>