[Spring Boot] properties 등록하기 (@PropertySource)

개요

Spring Boot로 프로젝트를 실행하면 기본적으로 application.properties를 참조하여 스프링이 실행 되지만, 스프링에 관련 없는 properties는 따로 설정파일을 만들어 빼고 싶은데, xml 설정파일이 없으니 어디에 추가해야 할지 막연했다. 검색을 하다보니 어노테이션에 properties 파일을 등록하면 사용이 가능했다.

예제

먼저 config.properties라는 파일을 resource 폴더에 생성했다.


config.properties

name=jekalmin


그리고 Application.java에 어노테이션을 이용하여 등록해주었다.


Application.java

package com.tistory.jekalmin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan
@EnableAutoConfiguration
@PropertySource("config.properties")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

마지막으로 컨트롤러를 생성하여 잘 가져오는지 테스트하였다.


TestController.java

package com.tistory.jekalmin;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test")
public class TestController {

    @Value("${name}")
    String name;

    @RequestMapping("/index")
    public void index(){
        System.out.println("name : " + name);
    }
}


결과는 다음과 같았다.

name : jekalmin

config.properties가 무사히 스프링에 등록된 것을 확인할 수 있다.