목차

SpringBoot Properties

기본값 설정

testing:
  my:
    username: ${external.username:system}
    password: ${external.password:test}
testing:
  my:
    username: ${external.username:user}
    password: ${external.password:#{' test'}}
@Value("${testing.my.username}")
private String username;
 
@Value("${testing.my.password}")
private String password;

profile 별 설정

a:
  b:
    c: default value
---
spring.profiles: local
# 기본값 그대로 사용

---
spring.profiles: develop
a:
  b:
    c: develop-value
---
spring.profiles: production
a:
  b:
    c: production-value

profile include

별도 Yaml로 PropertySource 적재 방식

// 일반 Bean으로 만들어 주입
@Autowired
private ConfigurableEnvironment env;
 
@Bean
@Order(-1)
PropertySource consumerPropertySource() throws IOException {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    PropertySource propertySource =
        loader.load("consumers", new ClassPathResource("consumer.yml"), "develop");
    env.getPropertySources().addLast(propertySource);
    return propertySource;
}
// ApplicationContextInitializerApplicationContextInitializer 구현
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
  try {
    Resource resource = applicationContext.getResource("classpath:application.yml");
    YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
    PropertySource<?> yamlTestProperties = sourceLoader.load("yamlTestProperties", resource, null);
    applicationContext.getEnvironment().getPropertySources().addLast(yamlTestProperties);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

YAML을 Property 객체로 변환하기

YAML을 ''@PropertySource''로 사용하기

@PropertySource(
    value = "classpath:foo.yml", 
    factory = YamlPropertySourceFactory.class
)
public class YamlPropertySourceFactory implements PropertySourceFactory {
 
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) 
      throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());
 
        Properties properties = factory.getObject();
 
        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
    }
}

@ConfigurationProperties

PropertySource과 properties 로그로 남기기

@Component
public class LoadedConfigFileListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {
 
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        MutablePropertySources propertySources = event.getApplicationContext().getEnvironment().getPropertySources();
        Iterator<PropertySource<?>> propertySourceIterator = propertySources.iterator();
        propertySourceIterator.forEachRemaining(propertySource -> log.info("Successfully loaded: \"{}\" ({}) into application context", propertySource.getName(), propertySource.getSource()));
    }
 
    @Override
    public int getOrder() {
        return ConfigFileApplicationListener.DEFAULT_ORDER + 1;
    }
}

모든 properties 로그로 남기기

@Component
public class PropertyLogger  {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyLogger.class);
 
    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
        final Environment env = event.getApplicationContext().getEnvironment();
        LOGGER.info("====== Environment and configuration ======");
        LOGGER.info("Active profiles: {}", Arrays.toString(env.getActiveProfiles()));
        final MutablePropertySources sources = ((AbstractEnvironment) env).getPropertySources();
        StreamSupport.stream(sources.spliterator(), false)
                .filter(ps -> ps instanceof EnumerablePropertySource)
                .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
                .flatMap(Arrays::stream)
                .distinct()
                .filter(prop -> !(prop.contains("credentials") || prop.contains("password")))
                .forEach(prop -> LOGGER.info("{}: {}", prop, env.getProperty(prop)));
        LOGGER.info("===========================================");
    }
}

addional property 파일지정

spring.config.additional-location=classpath:/custom-config,file:./custom-config

JSON을 통한 Override

EnvironmentPostProcessor 를 통한 프라퍼티 값 후처리

YAML Duration

참고