yml 정보 클래스로 가져오기

단비·2023년 4월 27일
0

학습

목록 보기
24/66

참고

application.yml에서 가져오기

1. yml에 필요한 정보 기입

aes:
  key: "secreyKey"

2. build.gradle에 dependency 추가

annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"  

3. yml 정보를 가져다 쓸 클래스 생성

  • getter, setter가 필요하므로 Data 어노테이션으로 대체
  • @Configuration 적용이 필요함
  • @ConfigurationProperties의 prefix에 그룹변수명 기입
@Configuration
@Data
@ConfigurationProperties(prefix = "aes")
public class ApplicationSetting {
    private String key;
}

4. 사용하기

@Component
@RequiredArgsConstructor
public class AES256 {
    private final ApplicationSetting applicationSetting;





별도 yml에서 가져오기

1,2 번은 동일하게 세팅

1. factory 생성

PropertySource에 yml을 read할 수 있는 factory가 없기 때문에 임의로 생성

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

2. yml 정보를 가져다 쓸 클래스 생성

@Configuration
@Data
@PropertySource(value = "classpath:aes.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "aes")
public class ApplicationSetting {
    private String key;
}

사용은 위와 동일하게 사용!

profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글