티스토리 뷰

Spring

스프링 부트 활용(2) - 외부 설정

도라지보다더덕 2020. 6. 1. 18:59

외부 설정

각종 설정값들을 application의 안이나 밖에 정의하는 기능으로 application.properties와 같은 설정 파일을 이용해서 설정해줍니다.

application.properties는 스프링 부트가 구동 시 자동으로 로딩하는 해주는 설정 파일입니다.

 

application.properties 내부에 정의된 값들은 @Value 어노테이션을 이용해서 사용가능합니다. 아주 기본적인 방법이지만 값을 정확히 써야하므로 자주 사용하지는 않는다고 합니다. 

 

@Value를 사용한 방법

 

application.properties에 dibtd.name = dibtd 를 작성하고 @Value를 통해 확인하면

@Component
public class SampleRunner implements ApplicationRunner {
    @Value("${dibtd.name}")
    private String name;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("---------------");
        System.out.println(name);
        System.out.println("---------------");
    }
}

위 클래스는 SampleRunner 클래스로 ApplicationRunner를 상속받아 run 메소드를 오버라이딩한 것입니다.

 

제대로 출력되어 나타납니다!

 

 

 

하지만 @Value 보다 더 편리하게 사용하는 방법이 있습니다. 바로 Bean으로 등록해서 사용하는 방법인데요.

application.properties에 prefix가 같은 값들이 여러 개 존재할 경우 따로 Bean으로 등록해서 사용하는 것이 더 편리하다고 하네요

 

application.properteis에 

dibtd.age = ${random.int}
dibtd.blog = dibtd Blog

 

를 추가하고 다음과 같이 SampleProperties 클래스를 만들어줍니다. ( ${random.int}은 int 형 랜덤값을 생성해줍니다)

@Component
@ConfigurationProperties("dibtd")
public class SampleProperties {
    private String name;
    private int age;
    private String blog;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getBlog() {
        return blog;
    }

    public void setBlog(String blog) {
        this.blog = blog;
    }


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

@ConfigurationProperties("dibtd") 어노테이션을 이용하면 스프링 부트에서 인자로 넘겨준 스트링(dibtd)에 해당하는 prefix를 properties에서 찾아 바인딩해줍니다. 따라서 getter와 setter가 반드시 필요합니다.

 

 

SampleRunner에 빈을 주입해주고 직접 확인해보면

@Component
public class SampleRunner implements ApplicationRunner {
    @Autowired
    SampleProperties sampleProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("---------------");
        System.out.println(sampleProperties.getName());
        System.out.println(sampleProperties.getAge());
        System.out.println(sampleProperties.getBlog());
        System.out.println("---------------");
    }
}

 

이런식으로 주입받아서 사용가능하다

 

 

 

우선순위

위에서 말했듯 설정값을 정의하는 방법은 매우 다양합니다. 그 중 일부분의 우선순위를 보면 다음과 같습니다.

 

프로퍼티 우선 순위

  1. 유저 홈 디렉토리에 있는 spring-boot-dev-tools.properties
  2. 테스트에 있는 @TestPropertySource
  3. @SpringBootTest 애노테이션의 properties 애트리뷰트
  4. 커맨드 라인 아규먼트
  5. SPRING_APPLICATION_JSON (환경 변수 또는 시스템 프로퍼티) 에 들어있는 프로퍼티
  6. ServletConfig 파라미터
  7. ServletContext 파라미터
  8. java:comp/env JNDI 애트리뷰트
  9. System.getProperties() 자바 시스템 프로퍼티
  10. OS 환경 변수
  11. RandomValuePropertySource
  12. JAR 밖에 있는 특정 프로파일용 application properties
  13. JAR 안에 있는 특정 프로파일용 application properties
  14. JAR 밖에 있는 application properties
  15. JAR 안에 있는 application properties
  16. @PropertySource
  17. 기본 프로퍼티 (SpringApplication.setDefaultProperties)

application.properties 

  1. file:./config/
  2. file:./
  3. classpath:/config/
  4. classpath:/

 

reference


inflearn - 백기선 스프링 부트 개념과 활용

'Spring' 카테고리의 다른 글

스프링 부트 활용(1) - application class  (0) 2020.05.21
1. 스프링 부트 특징  (0) 2020.05.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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 31
글 보관함