← Back to Home

SpringBoot Configuration에서 값 가져오기 - @Value

## SpringBoot 의 Configuration

SpringBoot는 여러가지 Configuration을 application.properties에 담아 사용한다.

application.properties를 사용 해도 되지만 application.yml도 지원 하기 때문에, 새로 만들어 Hierarchy를 표현해서 보기 편하도록 작성 하는 방법도 있다.

더불어서, 이 설정파일인 application.yml의 값들을 불러와서 사용 하는 @Value 어노테이션을 간단히 정리 해 보려고 한다.

## SpringBoot Configuration

SpringBoot stores various configurations in application.properties.

While you can use application.properties, SpringBoot also supports application.yml, which allows you to express hierarchy for better readability.

Additionally, I want to briefly cover the @Value annotation, which is used to retrieve values from the configuration file application.yml.

## application.yml 설정하기

이전에 application.yml을 사용 한 글이 있었는데, 그 글과 유사하게 작성 해 보려고 한다.

다만 통상적인 db세팅이나 서버 포트 세팅같은 부분들 외에, 특정 값을 가져오는 것을 한번 만들어 보려고 한다

## Setting up application.yml

I have previously written about using application.yml, and I will write this in a similar manner.

However, aside from typical database settings or server port settings, I want to demonstrate how to retrieve specific values.

# application.yml
myspring:
  test:
  name: wool
  age: 20
 
myspringListTest: banana,orange,apple
기본적인 세팅 외에, myspring이라는 이름 아래에 test.name, test.age 등을 만들어 놓았다.

접근 할 때에는 그냥 . 을 뒤에 붙여서 하위 요소들로 접근 해 주면 된다.

Besides the basic settings, I have created test.name, test.age, etc. under the name myspring.

When accessing these values, simply append . to navigate to the child elements.

## Test Code 작성

해당하는 값들을 불러 올 수 있는 코드를 만들고 테스트 해 보자.

테스트를 위해 ConfigurationAnnotationTests 클래스를 만들고, 간단한 테스트를 작성 해 보려고 한다

테스트코드를 작성 할 ConfigurationAnnotationTests 클래스를 준비한다

## Writing Test Code

Let's create code that can retrieve these values and test it.

For testing, I will create a ConfigurationAnnotationTests class and write a simple test.

Prepare the ConfigurationAnnotationTests class where we will write the test code.

ConfigurationAnnotationTest.java

package com.wool.springconf;
 
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.List;
 
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationAnnotationTests{
 
    // 코드를 작성 할 부분
 
}
코드들을 하나씩 작성 해 보자. 위의 application.yml 파일에 작성 된 설정값들을 가져 와 보자
Let's write the code step by step. Let's retrieve the configuration values written in the application.yml file above.
// 위 내용 생략
@Value("${myspring.test.name}")
private String mySpringTestName; // a
 
@Value("${myspring.test.age}")
private int mySpringTestAge; // b
 
@Value("${myspringListTest}")
private String[] mySpringArray; // c
 
@Value("$#{'${myspringListTest}'.split(',')}")
private List<String> mySpringList;
`@Value` 어노테이션은 configuration 값에 접근 할 수 있게 해 준다
  • a) "${myspring.test.name}" 는 myspring 하위의 test에 접근 한 후, 그 아래에 있는 name에 접근한다는 내용이다. 해당하는 값이 @Value 어노테이션 안에 넣어져 있고, 대응되는 mySpringTestName에 application.yml에서 작성한 wool이 저장된다
  • b) "${myspring.test.age}" 도 마찬가지로, myspring하위의 test에 있는 age값에 접근한다는 명시이고, 해당 값을 mySpringTestAge에 저장한다
  • c,d) myspringListTest 값은, application.yml값을 보면 다른 값과 조금 다르게 myspringListTest: banana,orange,apple 이렇게 값이 묶여있다. 두가지 방법으로 받아 줄 수 있다 – c) String[] mySpringArray 처럼, 리스트에 대입해서, 리스트 내부에 값을 저장해서 하나씩 값을 확인 해 줄 수 있다– d) List<String> mySpringList도 동일하게 받아 줄 수 있다
The `@Value` annotation allows access to configuration values.
  • a) "${myspring.test.name}" means accessing test under myspring, then accessing name under it. This value is placed inside the @Value annotation, and the corresponding mySpringTestName stores wool as written in application.yml.
  • b) "${myspring.test.age}" similarly indicates accessing the age value in test under myspring, and stores that value in mySpringTestAge.
  • c,d) The myspringListTest value is slightly different from other values in application.yml - it's bundled as myspringListTest: banana,orange,apple. It can be received in two ways:
    • c) Like String[] mySpringArray, you can assign it to a list and store values inside the list to check them one by one.
    • d) List<String> mySpringList can also receive it the same way.
## 전체 TestCode
## Complete Test Code
    package com.wool.springconf;
 
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
 
    import java.util.List;
 
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class ConfigurationAnnotationTests{
 
    	@Value("${myspring.test.name}")
    	private String mySpringTestName; // a
 
    	@Value("${myspring.test.age}")
    	private int mySpringTestAge; // b
 
    	@Value("${myspringListTest}")
    	private String[] mySpringArray; // c
 
    	@Value("$#{'${myspringListTest}'.split(',')}")
    	private List<String> mySpringList;
 
    	@Test
    	public void valueAnnotationTest(){
 
    		Assert.assertEquals(mySpringTestName, "wool");
    		Assert.assertEquals(mySpringTestAge, 20);
 
    		Assert.assertEquals(mySpringArray[0], "banana");
    		Assert.assertEquals(mySpringArray[1], "orange");
    		Assert.assertEquals(mySpringArray[2], "apple");
 
    		Assert.assertEquals(mySpringList.get(0), "banana");
    		Assert.assertEquals(mySpringList.get(1), "orange");
    		Assert.assertEquals(mySpringList.get(2), "apple");
    	}
 
    }
위의 테스트코드를 실행하면, 우리가 작성한 `application.yml` 의 값들을 가져와서 기대하는 값과 비교하여 서로 맞는지 확인한다.

값을 잘 가져왔다면 테스트가 성공하는 것을 볼 수 있다

When you run the test code above, it retrieves the values from our `application.yml` and compares them with the expected values to verify they match.

If the values are retrieved correctly, you will see the test succeed.