반응형

@Value

설명

  • 스프링은 application.properties에 정의된 값을 @Value를 통해 사용할 수 있는 방법을 제공한다.

application.properties

message=Hello World
student.names=john, jane, tyler
fruit.names={'apple', 'banana'}
fruit.counts={apple : 1, banana : 2}

ExamInfoProperties

@Data
@Component
public class ExamInfoProperties {
    @Value("${message}")
    private String message;

    @Value("${student.names}")
    private String[] studentNames1;

    @Value("${student.names}")
    private List<String> studentNames2;

    @Value("#{'${student.names}'.split(',')}")
    private List<String> studentNames3;

    @Value("#{${fruit.names}}")
    private List<String> fruitNames;

    @Value("#{${fruit.counts}}")
    private Map<String, Integer> fruitCounts;

    @Value("#{${fruit.counts}.apple}")
    private Integer appleCount1;

    @Value("#{${fruit.counts}['apple']}")
    private Integer appleCount2;
}

ValueTest

@SpringBootTest
public class ValueTest {
    @Autowired
    private ExamInfoProperties examInfoProperties;

    @Test
    public void testValues() {
        assertEquals("Hello World", examInfoProperties.getMessage());
        assertArrayEquals(new String[]{"john", "jane", "tyler"}, examInfoProperties.getStudentNames1());
        assertEquals(Arrays.asList("john", "jane", "tyler"), examInfoProperties.getStudentNames2());
        assertEquals(Arrays.asList("john", " jane", " tyler"), examInfoProperties.getStudentNames3());
        assertEquals(Arrays.asList("apple", "banana"), examInfoProperties.getFruitNames());
        assertEquals(Map.of("apple", 1, "banana", 2), examInfoProperties.getFruitCounts());
        assertEquals(1, examInfoProperties.getAppleCount1());
        assertEquals(1, examInfoProperties.getAppleCount2());
    }
}

application.yml 파일 활용하기

설명

  • application.properties 대신에 application.yml을 사용할 수도 있다.

application.yml

message: "Hello World"
student:
  names: "john, jane, tyler"
fruit:
  names: "{'apple', 'banana'}"
  counts: "{apple : 1, banana : 2}"

별도 properties 파일 지정하기

설명

  • @PropertySource를 활용하여 application.properties가 아닌 별도 properties 파일 정보를 로딩할 수 있다.
  • 아래는 ~/src/main/resources/exam-info/exam-info.properties 파일을 로딩하는 예시

ExamInfoProperties

@Data
@Component
@PropertySource("classpath:exam-info/exam-info.properties") // 추가
public class ExamInfoProperties { ... }

별도 yml 파일 지정하기

설명

  • @PropertySource를 활용하여 별도 yml 파일 정보를 로딩할 수 있다.
  • 아래는 ~/src/main/resources/exam-info/exam-info.yml 파일을 로딩하는 예시

YamlPropertySourceFactory

  • 기본적으로 @PropertySource는 YAML 파일을 로드하지 않으므로 사용자 정의 PropertySourceFactory를 만들어 사용해야 한다.
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());
        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), factory.getObject());
    }
}

ExamInfoProperties

@Data
@Component
@PropertySource(value = "classpath:exam-info/exam-info.yml", factory = YamlPropertySourceFactory.class) // 추가
public class ExamInfoProperties { ... }

properties 파일 경로를 wild card로 지정하기

설명

  • PropertySourcesPlaceholderConfigurer를 활용하면 properties 파일 경로를 wild card로 지정할 수 있다.
  • 아래는 ~/src/main/resources/exam-info/*.properties 파일을 로딩하는 예시

AppConfig

@Configuration
public class AppConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() throws IOException {
        PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertyConfigurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:exam-info/*.properties"));
        return propertyConfigurer;
    }
}

ExamInfoProperties

@Data
@Component
public class ExamInfoProperties { ... }

yml 파일 경로를 wild card로 지정하기

설명

  • YamlPropertySourceFactory 코드를 수정하여 활용하면 yml 파일 경로를 wild card로 지정할 수 있다.
  • 아래는 ~/src/main/resources/exam-info/*.yml 파일을 로딩하는 예시

YamlPropertySourceFactory

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(new PathMatchingResourcePatternResolver().getResources(((ClassPathResource) encodedResource.getResource()).getPath()));
        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), factory.getObject());
    }
}

ExamInfoProperties

@Data
@Component
@PropertySource(value = "classpath:exam-info/*.yml", factory = YamlPropertySourceFactory.class) // 추가
public class ExamInfoProperties { ... }

참고

반응형

'Development > Spring' 카테고리의 다른 글

[Spring] Replication  (0) 2021.11.15
[Spring] @ConfigurationProperties  (0) 2021.08.02
[Spring] Sharding  (0) 2021.07.07
[Spring] Thymeleaf  (0) 2021.06.26
[Spring] Model Mapping  (0) 2021.06.13

+ Recent posts